Maximize total count from the given Array
Last Updated :
18 Sep, 2023
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__
OutputMaximum value is : 11
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Approach 2: Greedy Algorithm
- Initialize two variables include and exclude as 0, representing the maximum sum including and the excluding the current element, respectively.
- Iterate through each element num in input array:
- Calculate the new value of include as the sum of the exclude and num.
- Update the value of exclude as the maximum of the include and exclude.
- The final result will be the maximum of the include and exclude.
Implementation :
C++
#include <iostream>
#include <vector>
#include <algorithm>
int GFG(const std::vector<int>& arr) {
int n = arr.size();
if (n == 0) return 0;
if (n == 1) return arr[0];
std::vector<int> dp(n);
dp[0] = arr[0];
dp[1] = std::max(arr[0], arr[1]);
for (int i = 2; i < n; i++) {
dp[i] = std::max(dp[i - 1], dp[i - 2] + arr[i]);
}
return dp[n - 1];
}
int maximizeSumGreedy(const std::vector<int>& arr) {
int include = 0, exclude = 0;
for (int num : arr) {
int new_include = exclude + num;
exclude = std::max(include, exclude);
include = new_include;
}
return std::max(include, exclude);
}
int main() {
std::vector<int> inputArray = {1, 2, 5, 4, 5};
int resultDP = GFG(inputArray);
int resultGreedy = GFG(inputArray);
std::cout << "Using Dynamic Programming:" << std::endl;
std::cout << resultDP << std::endl;
std::cout << "Using Greedy Algorithm:" << std::endl;
std::cout << resultGreedy << std::endl;
return 0;
}
Java
import java.util.List;
class Main {
public static int GFG(List<Integer> arr) {
int n = arr.size();
if (n == 0)
return 0;
if (n == 1)
return arr.get(0);
int[] dp = new int[n];
dp[0] = arr.get(0);
dp[1] = Math.max(arr.get(0), arr.get(1));
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + arr.get(i));
}
return dp[n - 1];
}
public static int maximizeSumGreedy(List<Integer> arr) {
int include = 0, exclude = 0;
for (int num : arr) {
int new_include = exclude + num;
exclude = Math.max(include, exclude);
include = new_include;
}
return Math.max(include, exclude);
}
public static void main(String[] args) {
List<Integer> inputArray = List.of(1, 2, 5, 4, 5);
int resultDP = GFG(inputArray);
int resultGreedy = GFG(inputArray);
System.out.println("Using Dynamic Programming:");
System.out.println(resultDP);
System.out.println("Using Greedy Algorithm:");
System.out.println(resultGreedy);
}
}
Python3
# Python code for the above approach
# Function to Calculate the maximum sum using dynamic programming
def GFG(arr):
n = len(arr)
if n == 0:
return 0
if n == 1:
return arr[0]
# Initialize an array
dp = [0] * n
dp[0] = arr[0]
dp[1] = max(arr[0], arr[1])
# Traversing the loop and Calculating the maximum sum till index i
for i in range(2, n):
dp[i] = max(dp[i - 1], dp[i - 2] + arr[i])
return dp[n - 1]
# Function to Calculate the maximum sum using the greedy approach
def maximizeSumGreedy(arr):
# Initialize a variable to store the maximum sum including the current element
include = 0
# # Initialize a variable to store the maximum sum excluding the current element
exclude = 0
# Traverse the array and calculate the maximum sum using the greedy approach
for num in arr:
new_include = exclude + num
exclude = max(include, exclude)
include = new_include
return max(include, exclude)
# Driver Code
if __name__ == "__main__":
inputArray = [1, 2, 5, 4, 5]
resultDP = GFG(inputArray)
resultGreedy = maximizeSumGreedy(inputArray)
print("Using Dynamic Programming:")
print(resultDP)
print("Using Greedy Algorithm:")
print(resultGreedy)
# This code is contributed by Pushpesh Raj
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to find the maximum sum of a subsequence
// using Dynamic Programming
static int GFG(List<int> arr)
{
int n = arr.Count;
if (n == 0) return 0;
if (n == 1) return arr[0];
List<int> dp = new List<int>(n);
dp.Add(arr[0]);
dp.Add(Math.Max(arr[0], arr[1]));
for (int i = 2; i < n; i++)
{
dp.Add(Math.Max(dp[i - 1], dp[i - 2] + arr[i]));
}
return dp[n - 1];
}
// Function to find the maximum sum of a subsequence
// using Greedy Algorithm
static int MaximizeSumGreedy(List<int> arr)
{
int include = 0, exclude = 0;
foreach (int num in arr)
{
int new_include = exclude + num;
exclude = Math.Max(include, exclude);
include = new_include;
}
return Math.Max(include, exclude);
}
static void Main()
{
List<int> inputArray = new List<int> { 1, 2, 5, 4, 5 };
int resultDP = GFG(inputArray);
int resultGreedy = MaximizeSumGreedy(inputArray);
Console.WriteLine("Using Dynamic Programming:");
Console.WriteLine(resultDP);
Console.WriteLine("Using Greedy Algorithm:");
Console.WriteLine(resultGreedy);
}
}
JavaScript
// Function to Calculate the maximum sum using dynamic programming
const GFG = (arr) => {
const n = arr.length;
if (n === 0) {
return 0;
}
if (n === 1) {
return arr[0];
}
// Initialize an array
const dp = new Array(n).fill(0);
dp[0] = arr[0];
dp[1] = Math.max(arr[0], arr[1]);
// Traversing the loop and Calculating the maximum sum till index i
for (let i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + arr[i]);
}
return dp[n - 1];
};
// Function to Calculate the maximum sum using the greedy approach
const maximizeSumGreedy = (arr) => {
// Initialize a variable to store the maximum sum including the current element
let include = 0;
// Initialize a variable to store the maximum sum excluding the current element
let exclude = 0;
// Traverse the array and calculate the maximum sum using the greedy approach
for (let num of arr) {
const new_include = exclude + num;
exclude = Math.max(include, exclude);
include = new_include;
}
return Math.max(include, exclude);
};
// Driver Code
const inputArray = [1, 2, 5, 4, 5];
const resultDP = GFG(inputArray);
const resultGreedy = maximizeSumGreedy(inputArray);
console.log("Using Dynamic Programming:");
console.log(resultDP);
console.log("Using Greedy Algorithm:");
console.log(resultGreedy);
output :
Using Dynamic Programming:
11
Using Greedy Algorithm:
11
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read