Maximum items that can be bought from the cost Array based on given conditions

18 Feb, 2022
Given an array arr[] of size N where every index in the array represents the cost of buying an item and two numbers P, K. The task is to find the maximum number of items which can be bought such that: 
If some i-th object is bought from the array, the remaining amount becomes P – arr[i].We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items).
If some i-th object is bought from the array, the remaining amount becomes P – arr[i].
We can buy K items, not necessarily consecutive, at a time by paying only for the item whose cost is maximum among them. Now, the remaining amount would be P – max(cost of K items).
Examples: 
Input: arr[] = {2, 4, 3, 5, 7}, P = 6, K = 2Output: 3 Explanation: We can buy the first item whose cost is 2. So, the remaining amount is P = 6 – 2 = 4. Now, we can choose the second and third item and pay for the maximum one which is max(4, 3) = 4, and the remaining amount is 4 – 4 = 0. Therefore, the total number of items bought is 3. 
Input: arr[] = {2, 4, 3, 5, 7}, P = 11, K = 2Output: 4 Explanation: We can buy the first and third item together and pay for only the maximum one which is max(2, 3) = 3. The remaining amount is P = 11 – 3 = 8. Now, we can buy the second and fourth item and pay for the maximum one which is max(4, 5) = 5. The remaining amount is P = 8 – 5 = 3. Now, we cant buy any item further. 
Approach: The idea is to use the concept of sorting and prefix sum array. 
Sort the given array arr[].
Find the prefix sum for the array arr[].
The idea behind sorting is that the maximum number of items can be bought only when we buy the items with less cost. This type of algorithm is known as a greedy algorithm.
And, we use the prefix sum array to find the cost of buying the items.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to find the// maximum number of items// that can be bought from// the given cost array #include <bits/stdc++.h>using namespace std; // Function to find the// maximum number of items// that can be bought from// the given cost arrayint number(int a[], int n, int p, int k){    // Sort the given array    sort(a, a + n);     // Variables to store the prefix    // sum, answer and the counter    // variables    int pre[n] = { 0 }, val, i,        j, ans = 0;     // Initializing the first element    // of the prefix array    pre[0] = a[0];     // If we can buy at least one item    if (pre[0] <= p)        ans = 1;     // Iterating through the first    // K items and finding the    // prefix sum    for (i = 1; i < k - 1; i++) {        pre[i] = pre[i - 1] + a[i];         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }     pre[k - 1] = a[k - 1];     // Finding the prefix sum for    // the remaining elements    for (i = k - 1; i < n; i++) {        if (i >= k) {            pre[i] += pre[i - k] + a[i];        }         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }     return ans;} // Driver codeint main(){    int n = 5;    int arr[] = { 2, 4, 3, 5, 7 };    int p = 11;    int k = 2;     cout << number(arr, n, p, k) << endl;     return 0;}
// Java program to find the maximum// number of items that can be bought// from the given cost arrayimport java.io.*;import java.util.*; class GFG{ // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n,                  int p, int k){         // Sort the given array    Arrays.sort(a);     // Variables to store the prefix    // sum, answer and the counter    // variables    int[] pre = new int[n];    int val, i, j, ans = 0;     // Initializing the first element    // of the prefix array    pre[0] = a[0];     // If we can buy at least one item    if (pre[0] <= p)        ans = 1;     // Iterating through the first    // K items and finding the    // prefix sum    for(i = 1; i < k - 1; i++)    {        pre[i] = pre[i - 1] + a[i];         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }    pre[k - 1] = a[k - 1];     // Finding the prefix sum for    // the remaining elements    for(i = k - 1; i < n; i++)    {        if (i >= k)        {            pre[i] += pre[i - k] + a[i];        }         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }    return ans;} // Driver codepublic static void main(String[] args){    int n = 5;    int[] arr = { 2, 4, 3, 5, 7 };    int p = 11;    int k = 2;     System.out.println(number(arr, n, p, k));}} // This code is contributed by akhilsaini
# Python3 program to find the maximum# number of items that can be bought# from the given cost array # Function to find the maximum# number of items that can be# bought from the given cost arraydef number(a, n, p, k):         # Sort the given array    a.sort()         # Variables to store the prefix    # sum, answer and the counter    # variables    pre = [ ]    for i in range(n):        pre.append(0)             ans = 0    val = 0    i = 0    j = 0         # Initializing the first element    # of the prefix array    pre[0] = a[0]         # If we can buy at least one item    if pre[0] <= p:        ans = 1             # Iterating through the first    # K items and finding the    # prefix sum    for i in range(1, k - 1):        pre[i] = pre[i - 1] + a[i]                 # Check the number of items        # that can be bought        if pre[i] <= p:            ans = i + 1             pre[k - 1] = a[k - 1]         # Finding the prefix sum for    # the remaining elements    for i in range(k - 1, n):        if i >= k:            pre[i] += pre[i - k] + a[i]                     # Check the number of items        # that can be bought        if pre[i] <= p:            ans = i+ 1             return ans     # Driver coden = 5arr = [ 2, 4, 3, 5, 7 ]p = 11k = 2 print(number(arr, n, p, k)) # This code is contributed by ishayadav181
// C# program to find the maximum// number of items that can be// bought from the given cost arrayusing System;using System.Collections; class GFG{   // Function to find the// maximum number of items// that can be bought from// the given cost arraystatic int number(int[] a, int n,                  int p, int k){         // Sort the given array    Array.Sort(a);     // Variables to store the prefix    // sum, answer and the counter    // variables    int[] pre = new int[n];    int i, ans = 0;     // Initializing the first element    // of the prefix array    pre[0] = a[0];     // If we can buy at least one item    if (pre[0] <= p)        ans = 1;     // Iterating through the first    // K items and finding the    // prefix sum    for(i = 1; i < k - 1; i++)    {        pre[i] = pre[i - 1] + a[i];         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }     pre[k - 1] = a[k - 1];     // Finding the prefix sum for    // the remaining elements    for(i = k - 1; i < n; i++)    {        if (i >= k)        {            pre[i] += pre[i - k] + a[i];        }                 // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }    return ans;} // Driver codestatic public void Main (){    int n = 5;    int[] arr = { 2, 4, 3, 5, 7 };    int p = 11;    int k = 2;     Console.WriteLine(number(arr, n, p, k));}} // This code is contributed by akhilsaini
<script> // Javascript program to find the// maximum number of items// that can be bought from// the given cost array // Function to find the// maximum number of items// that can be bought from// the given cost arrayfunction number(a, n, p, k){    // Sort the given array    a.sort();     // Variables to store the prefix    // sum, answer and the counter    // variables    var pre = Array(n).fill(0), val, i,        j, ans = 0;     // Initializing the first element    // of the prefix array    pre[0] = a[0];     // If we can buy at least one item    if (pre[0] <= p)        ans = 1;     // Iterating through the first    // K items and finding the    // prefix sum    for (i = 1; i < k - 1; i++) {        pre[i] = pre[i - 1] + a[i];         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }     pre[k - 1] = a[k - 1];     // Finding the prefix sum for    // the remaining elements    for (i = k - 1; i < n; i++) {        if (i >= k) {            pre[i] += pre[i - k] + a[i];        }         // Check the number of items        // that can be bought        if (pre[i] <= p)            ans = i + 1;    }     return ans;} // Driver codevar n = 5;var arr = [2, 4, 3, 5, 7];var p = 11;var k = 2;document.write( number(arr, n, p, k)); </script>
4
 
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
ishayadav181
akhilsaini
rutvik_56
rohan07
simranarora5sos
prefix-sum
Arrays
Greedy
Sorting
prefix-sum
Arrays
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Introduction to Arrays
Dijkstra's shortest path algorithm | Greedy Algo-7
Write a program to print all permutations of a given string
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Activity Selection Problem | Greedy Algo-1