📌  相关文章
📜  所有前缀之和为负的最长子序列的长度

📅  最后修改于: 2021-10-28 02:02:37             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是找到最长子序列的长度,使得子序列每个索引处的前缀和为负。

例子:

方法:这个问题可以通过使用优先队列来解决。请按照以下步骤解决问题:

  • 初始化一个优先级队列,比如pq ,和一个变量,比如S0 ,以存储从元素到索引i形成的子序列的元素,并存储优先级队列中元素的总和。
  • 使用变量i在范围[0, N – 1] 上迭代并执行以下步骤:
    • 通过arr[i]增加S并将arr[i]推入pq。
    • 迭代直到S大于0 ,在每次迭代中,将S递减pq的顶部元素,然后弹出顶部元素。
  • 最后,完成上述步骤后,打印pq.size()作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the maximum length
// of a subsequence such that prefix sum
// of any index is negative
int maxLengthSubsequence(int arr[], int N)
{
    // Max priority Queue
    priority_queue pq;
 
    // Stores the temporary sum of a
    // prefix of selected subsequence
    int S = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        // Increment S by arr[i]
        S += arr[i];
 
        // Push arr[i] into pq
        pq.push(arr[i]);
 
        // Iterate until S
        // is greater than 0
        while (S > 0) {
 
            // Decrement S by pq.top()
            S -= pq.top();
 
            // Pop the top element
            pq.pop();
        }
    }
 
    // Return the maxLength
    return pq.size();
}
 
// Driver Code
int main()
{
    // Given Input
    int arr[6] = { -1, -3, 3, -5, 8, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    // Function call
    cout << maxLengthSubsequence(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.Collections;
import java.util.PriorityQueue;
 
public class GFG
{
 
    // Function to find the maximum length
    // of a subsequence such that prefix sum
    // of any index is negative
    static int maxLengthSubsequence(int arr[], int N)
    {
       
        // Max priority Queue
        PriorityQueue pq = new PriorityQueue<>(
            Collections.reverseOrder());
 
        // Stores the temporary sum of a
        // prefix of selected subsequence
        int S = 0;
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++)
        {
           
            // Increment S by arr[i]
            S += arr[i];
 
            // Add arr[i] into pq
            pq.add(arr[i]);
 
            // Iterate until S
            // is greater than 0
            while (S > 0)
            {
 
                // Decrement S by pq.peek()
                S -= pq.peek();
 
                // Remove the top element
                pq.remove();
            }
        }
 
        // Return the maxLength
        return pq.size();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { -1, -3, 3, -5, 8, 2 };
        int N = arr.length;
       
        // Function call
        System.out.println(maxLengthSubsequence(arr, N));
    }
}
 
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
 
# Function to find the maximum length
# of a subsequence such that prefix sum
# of any index is negative
def maxLengthSubsequence(arr, N):
     
    # Max priority Queue
    pq = []
 
    # Stores the temporary sum of a
    # prefix of selected subsequence
    S = 0
 
    # Traverse the array arr[]
    for i in range(N):
         
        # Increment S by arr[i]
        S += arr[i]
 
        # Push arr[i] into pq
        pq.append(arr[i])
 
        # Iterate until S
        # is greater than 0
        pq.sort(reverse = False)
         
        while (S > 0):
             
            # Decrement S by pq.top()
            # pq.sort(reverse=False)
            S = S - max(pq)
 
            # Pop the top element
            pq = pq[1:]
             
        # print(len(pq))
 
    # Return the maxLength
    return len(pq)
 
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    arr = [ -1, -3, 3, -5, 8, 2 ]
    N = len(arr)
     
    # Function call
    print(maxLengthSubsequence(arr, N))
     
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to find the maximum length
// of a subsequence such that prefix sum
// of any index is negative
static int maxLengthSubsequence(int []arr, int N)
{
    // Max priority Queue
    List pq = new List();
 
    // Stores the temporary sum of a
    // prefix of selected subsequence
    int S = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
    {
       
        // Increment S by arr[i]
        S += arr[i];
 
        // Push arr[i] into pq
        pq.Add(arr[i]);
         
        pq.Sort();
        // Iterate until S
        // is greater than 0
        while (S > 0) {
            pq.Sort();
            // Decrement S by pq.top()
            S -=  pq[pq.Count-1];
 
            // Pop the top element
            pq.RemoveAt(0);
        }
    }
 
    // Return the maxLength
    return pq.Count;
}
 
// Driver Code
public static void Main()
{
   
    // Given Input
    int []arr = { -1, -3, 3, -5, 8, 2 };
    int N = arr.Length;
   
    // Function call
    Console.Write(maxLengthSubsequence(arr, N));
     
}
}
 
// This code is contributed by ipg2016107.


Javascript


输出:
5

时间复杂度: O(N*log(N))
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程