Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Maximize total count from the given Array

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given an array nums of length N which contains two types of numbers, one which has the value zero, the second which is a positive integer, the task is to collect numbers from the below operations and return the maximum value you can collect.

  • If the given number is a positive integer, then it’s your choice, whether you can put it on the top of the queue or not.
  • Else, if the number is zero, then pick the topmost number from the queue and remove it.

Examples:

Input: N = 7, nums = [1, 2, 3, 0, 4, 5, 0]
Output: 8
Explanation: To maximize the total value do the following operation while iterating the nums[ ]:
nums[0] = 1, put on the top of the queue. Queue becomes: [1]
nums[1] = 2, put on the top of the queue. Queue becomes: [2, 1]
nums[2] = 3, put on the top of the queue. Queue becomes: [3, 2, 1]
nums[3] = 0, pick the top value from the queue and remove it. Total val = 3, and queue becomes: [2, 1]
nums[4] = 4, put on the top of the queue. Queue becomes: [4, 2, 1]
nums[5] = 5, put on the top of the queue. Queue becomes: [5, 4, 2, 1]
nums[6] = 0, pick the top value from the queue and remove it. Total val = 3 + 5 = 8, and queue becomes: [4, 2, 1]
Return val = 8.

Input: N = 8, nums = [5, 1, 2, 0, 0, 4, 3, 0]
Output: 11
Explanation: To maximize the total value do the following operation while iterating the nums[ ]:
nums[0] = 5,  put on the top of the queue. Queue becomes: [5]
nums[1] = 1, ignore this number. Queue remains: [5]
nums[2] = 2,  put on the top of the queue. Queue becomes: [2, 5]
nums[3] = 0, pick the top value from the queue and remove it. Total val = 0 + 2 = 2, and queue becomes: [5]
nums[4] = 0, pick the top value from the queue and remove it. Total val = 2 + 5 = 7, and queue becomes: [ ]
nums[5] = 4, put on the top of the queue. Queue becomes: [4]
nums[6] = 3, ignore this number. Queue remains: [4]
nums[7] = 0, pick the top value from the queue and remove it. Total val = 7 + 4 = 11, and queue becomes: [ ]
Return val = 11.

Approach: To solve the problem follow the below idea:

We will use a decreasing priority queue and store the positive integers in it, when we encounter zero we will take the peek() element (if it is not empty) from the priority queue and add it to the variable val.

Below are the steps for the above approach:

  • Initialize a decreasing priority queue.
  • Iterate the given array,
    • If you encounter any positive integer, add it to the priority queue.
    • Else, if you encounter a zero, check whether the priority queue is empty or not. If it is not empty, remove the top element from it and add it to the variable val which contains the current sum of the maximum value.
  • Return the final answer val.

Below is the code for the above approach:

C++




// C++ code for the above approach
 
#include <functional>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
 
// Function to calculate maximum value
int calculateMaxVal(vector<int>& nums, int N)
{
    priority_queue<int> decreasing;
 
    int val = 0;
    for (int i = 0; i < N; i++) {
        if (nums[i] == 0) {
            if (!decreasing.empty()) {
                val += (decreasing.top());
                decreasing.pop();
            }
        }
        else {
            decreasing.push(nums[i]);
        }
    }
 
    return val;
}
 
// Drivers code
int main()
{
 
    int N = 8;
    vector<int> nums = { 5, 1, 2, 0, 0, 4, 3, 0 };
 
    cout << "Maximum value is: " << calculateMaxVal(nums, N)
         << endl;
 
    return 0;
}


Java




// Java code for the above approach
 
import java.util.*;
 
class GFG {
 
    // Drivers code
    public static void main(String[] args)
    {
        int N = 8;
        int[] nums = { 5, 1, 2, 0, 0, 4, 3, 0 };
        System.out.println("Maximum value is : "
                           + calculateMaxVal(nums, N));
    }
 
    // Function to calculate maximum value
    public static int calculateMaxVal(int[] nums, int N)
    {
        PriorityQueue<Integer> decreasing
            = new PriorityQueue<Integer>(
                Collections.reverseOrder());
        int val = 0;
        for (int i = 0; i < N; i++) {
            if (nums[i] == 0) {
                if (!decreasing.isEmpty())
                    val += decreasing.remove();
            }
            else {
                decreasing.add(nums[i]);
            }
        }
 
        return val;
    }
}


Python3




# Python code for the above approach:
 
import heapq
 
# Function to calculate maximum value
 
 
def calculateMaxVal(nums):
    decreasing = []
    val = 0
    for num in nums:
        if num == 0:
            if decreasing:
                val += -heapq.heappop(decreasing)
        else:
            heapq.heappush(decreasing, -num)
    return val
 
 
nums = [5, 1, 2, 0, 0, 4, 3, 0]
print("Maximum value is: ", calculateMaxVal(nums))
 
# This code is contributed by lokesh.


C#




// C# code for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to calculate maximum value
    static int CalculateMaxVal(List<int> nums, int N)
    {
        // Create a priority queue to store decreasing
        // numbers
        PriorityQueue<int> decreasing
            = new PriorityQueue<int>(new Comparison<int>(
                (x, y) => y.CompareTo(x)));
        int val = 0;
 
        // Iterate through the array
        for (int i = 0; i < N; i++) {
            // If the element is 0, pop the maximum element
            // from the priority queue and add it to the
            // result
            if (nums[i] == 0) {
                if (decreasing.Count > 0) {
                    val += decreasing.Dequeue();
                }
            }
            else {
                // If the element is non-zero, add it to the
                // priority queue
                decreasing.Enqueue(nums[i]);
            }
        }
 
        return val;
    }
 
    // Driver's code
    static void Main(string[] args)
    {
        // Input
        int N = 8;
        List<int> nums
            = new List<int>() { 5, 1, 2, 0, 0, 4, 3, 0 };
 
        // Function call
        Console.WriteLine("Maximum value is: "
                          + CalculateMaxVal(nums, N));
    }
}
 
// Implementation of a priority queue using a heap
public class PriorityQueue<T> {
    private List<T> _heap;
    private Comparison<T> _comparison;
 
    public PriorityQueue() { _heap = new List<T>(); }
 
    public PriorityQueue(Comparison<T> comparison)
    {
        _heap = new List<T>();
        _comparison = comparison;
    }
 
    public void Enqueue(T item)
    {
        _heap.Add(item);
        int i = _heap.Count - 1;
        while (i > 0) {
            int j = (i - 1) / 2;
            if (_comparison == null) {
                if (((IComparable<T>)_heap[j])
                        .CompareTo(item)
                    <= 0) {
                    break;
                }
            }
            else {
                if (_comparison(_heap[j], item) <= 0) {
                    break;
                }
            }
            _heap[i] = _heap[j];
            i = j;
        }
        _heap[i] = item;
    }
 
    public T Dequeue()
    {
        int lastIndex = _heap.Count - 1;
        T frontItem = _heap[0];
        _heap[0] = _heap[lastIndex];
        _heap.RemoveAt(lastIndex);
 
        --lastIndex;
        int i = 0;
        while (true) {
            int left = i * 2 + 1;
            if (left > lastIndex) {
                break;
            }
            int right = left + 1;
            if (right <= lastIndex
                && (_comparison == null
                        ? ((IComparable<T>)_heap[left])
                                  .CompareTo(_heap[right])
                              > 0
                        : _comparison(_heap[left],
                                      _heap[right])
                              > 0)) {
                left = right;
            }
            if (_comparison == null
                    ? ((IComparable<T>)_heap[i])
                              .CompareTo(_heap[left])
                          <= 0
                    : _comparison(_heap[i], _heap[left])
                          <= 0) {
                break;
            }
            T tmp = _heap[i];
            _heap[i] = _heap[left];
            _heap[left] = tmp;
            i = left;
        }
        return frontItem;
    }
 
    public int Count
    {
        get { return _heap.Count; }
    }
}


Javascript




// Function to calculate maximum value
function calculateMaxVal(nums) {
  let decreasing = [];
 
  let val = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) {
      if (decreasing.length > 0) {
        val += decreasing[0];
        decreasing.shift();
      }
    } else {
      decreasing.push(nums[i]);
      decreasing.sort((a, b) => b - a);
    }
  }
 
  return val;
}
 
// Driver code
let nums = [5, 1, 2, 0, 0, 4, 3, 0];
console.log("Maximum value is: ", calculateMaxVal(nums));
// akashish__


Output

Maximum value is : 11

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Last Updated : 25 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials