Maximum product of an Array after subtracting 1 from any element N times Last Updated : 06 Dec, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report Given an array arr[] of positive integers of size M and an integer N, the task is to maximize the product of array after subtracting 1 from any element N number of times Examples: Input: M = 5, arr[] = {5, 1, 7, 8, 3}, N = 2Output: 630Explanation: After subtracting 1 from arr[3] 2 times, array becomes {5, 1, 7, 6, 3} with product = 630Input: M = 2, arr[] = {2, 2}, N = 4Output: 0Explanation: After subtracting 2 from arr[0] and arr[1] 2 times each, array becomes {0, 0} with product = 0 Approach: The task can be solved with the help of max-heap Follow the below steps to solve the problem: Insert all the elements inside a max-heapPop the top element from the max- heap, and decrement 1 from it, also decrement NInsert the popped element back to max-heapContinue this process till N > 0The maximum product will be the product of all the elements inside the max-heap Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the maximum // product of the array int getMax(int m, int arr[], int n) { // Max-heap priority_queue<int> q; // Store all the elements inside max-heap for (int i = 0; i < m; i++) q.push(arr[i]); // n operations while (n--) { int x = q.top(); q.pop(); // Decrement x --x; // Push back x inside the heap q.push(x); } // Store the max product possible int ans = 1; while (!q.empty()) { ans *= q.top(); q.pop(); } return ans; } // Driver Code int main() { int M = 5; int arr[5] = { 5, 1, 7, 8, 3 }; int N = 2; cout << getMax(M, arr, N); } Java // Java program for the above approach import java.util.*; class GFG { // Function to find the maximum // product of the array static Integer getMax(int m, Integer arr[], int n) { // Max-heap PriorityQueue<Integer> q = new PriorityQueue<Integer>( Collections.reverseOrder()); // Store all the elements inside max-heap for (int i = 0; i < m; i++) q.add(arr[i]); // n operations while (n-- != 0) { Integer x = q.poll(); // Decrement x --x; // Push back x inside the heap q.add(x); } // Store the max product possible Integer ans = 1; while (q.size() != 0) { ans *= q.poll(); } return ans; } // Driver Code public static void main(String[] args) { int M = 5; Integer arr[] = { 5, 1, 7, 8, 3 }; int N = 2; System.out.println(getMax(M, arr, N)); } } // This code is contributed by Potta Lokesh Python3 # python program for the above approach from queue import PriorityQueue # Function to find the maximum # product of the array def getMax(m, arr, n): # Max-heap q = PriorityQueue() # Store all the elements inside max-heap for i in range(0, m): q.put(-arr[i]) # n operations while (n): n -= 1 x = -q.get() # Decrement x x -= 1 # Push back x inside the heap q.put(-x) # Store the max product possible ans = 1 while (not q.empty()): ans *= -q.get() return ans # Driver Code if __name__ == "__main__": M = 5 arr = [5, 1, 7, 8, 3] N = 2 print(getMax(M, arr, N)) # This code is contributed by rakeshsahni C# // C# program for the above approach using System; using System.Collections.Generic; public class GFG { // Function to find the maximum // product of the array static int getMax(int m, int []arr, int n) { // Max-heap List<int> q = new List<int>(); // Store all the elements inside max-heap for (int i = 0; i < m; i++){ q.Add(arr[i]); } q.Sort(); q.Reverse(); // n operations while (n-- != 0) { int x = q[0]; q.RemoveAt(0); // Decrement x --x; // Push back x inside the heap q.Add(x); q.Sort(); q.Reverse(); } // Store the max product possible int ans = 1; while (q.Count != 0) { ans *= q[0]; q.RemoveAt(0); } return ans; } // Driver Code public static void Main(String[] args) { int M = 5; int []arr = { 5, 1, 7, 8, 3 }; int N = 2; Console.WriteLine(getMax(M, arr, N)); } } // This code is contributed by shikhasingrajput JavaScript <script> // Javascript program for the above approach // Function to find the maximum // product of the array function getMax(m, arr, n) { // Max-heap let q = []; // Store all the elements inside max-heap for (let i = 0; i < m; i++) { q.push(arr[i]); } q.sort(); q.reverse(); // n operations while (n-- != 0) { let x = q[0]; q.splice(0, 1); // Decrement x --x; // Push back x inside the heap q.push(x); q.sort(); q.reverse(); } // Store the max product possible let ans = 1; while (q.length != 0) { ans *= q[0]; q.splice(0, 1); } return ans; } // Driver Code let M = 5; let arr = [5, 1, 7, 8, 3]; let N = 2; document.write(getMax(M, arr, N)); // This code is contributed by gfgking </script> Output630 Time Complexity: O(nlogm)Auxiliary Space: O(m) Comment More infoAdvertise with us Next Article Maximum product of an Array after subtracting 1 from any element N times S saurabh15899 Follow Improve Article Tags : Greedy Mathematical DSA Arrays STL +1 More Practice Tags : ArraysGreedyMathematicalSTL 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 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 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 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 Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like