Maximum count of integers to be chosen from given two stacks having sum at most K
Last Updated : 08 Mar, 2024
Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K.
Examples:
Input: stack1[ ] = { 60, 90, 120 }
stack2[ ] = { 100, 10, 10, 250 }, K = 130
Output: 3
Explanation: Take 3 numbers from stack1 which are 100 and 10 and 10.
Total sum 100 + 10 + 10 = 120
Input: stack1[ ] = { 60, 90, 120 }
stack2[ ] = { 80, 150, 80, 150 }, K = 740
Output: 7
Explanation: Select all the numbers because the value K is enough.
Approach: This problem cannot be solved using the Greedy approach because in greedy at each step the number having the minimum value will be selected but the first example fails according to this. This problem can be solved using prefix sum and binary search. calculate the prefix sum of both the stacks and now iterate for every possible value of 1st stack and take target which is (K - stack1[i]) and apply binary search on the second stack to take lower bound of stack2[].
Follow the steps mentioned below:
- Take two new stacks which are sumA[] and sumB[].
- Calculate the prefix of both the stacks stack1[] and stack2[].
- Iterate on the first stack.
- Now, take the remValueOfK variable and store (K - stack1[i]).
- If it is less than 0 so continue the loop.
- Else take the lower bound of the second stack.
- If the lower bound is greater than the size of the second stack or the value of the lower bound is greater than the value of remValueOfK just decrement the value of the lower bound variable.
- Store the maximum count of elements selected and return that as the final answer.
Below is the implementation of the above approach.
C++ // C++ code to implement the above approach #include <bits/stdc++.h> using namespace std; // Function to find the // maximum number of elements int maxNumbers(int stack1[], int N, int stack2[], int M, int K) { // Take prefix of both the stack vector<int> sumA(N + 1, 0); vector<int> sumB(M + 1, 0); for (int i = 0; i < N; i++) sumA[i + 1] = sumA[i] + stack1[i]; for (int i = 0; i < M; i++) sumB[i + 1] = sumB[i] + stack2[i]; // Calculate maxNumbers int MaxNumbers = 0; for (int i = 0; i <= N; i++) { // Calculate remaining value of K // after selecting numbers // from 1st stack int remValueOfK = K - sumA[i]; // If rem value of K is less than 0 // continue the loop if (remValueOfK < 0) continue; // Calculate lower bound int lowerBound = lower_bound(sumB.begin(), sumB.end(), remValueOfK) - sumB.begin(); // If size of lower bound is greater // than self stack size or // value of lower bound element // decrement lowerBound if (lowerBound > M or sumB[lowerBound] > remValueOfK) { lowerBound--; } // Store max possible numbers int books = i + lowerBound; MaxNumbers = max(MaxNumbers, books); } return MaxNumbers; } // Driver code int main() { int stack1[] = { 60, 90, 120 }; int stack2[] = { 100, 10, 10, 200 }; int K = 130; int N = 3; int M = 4; int ans = maxNumbers(stack1, N, stack2, M, K); cout << ans; return 0; }
Java // Java program to implement // the above approach import java.util.*; class GFG { static int lower_bound(int []a, int val) { int lo = 0, hi = a.length - 1; while (lo < hi) { int mid = (int)Math.floor(lo + (double)(hi - lo) / 2); if (a[mid] < val) lo = mid + 1; else hi = mid; } return lo; } // Function to find the // maximum number of elements static int maxNumbers(int []stack1, int N, int []stack2, int M, int K) { // Take prefix of both the stack int []sumA = new int[N + 1]; for(int i = 0; i < N + 1; i++) { sumA[i] = 0; } int []sumB = new int[M + 1]; for(int i = 0; i < M + 1; i++) { sumB[i] = 0; } for (int i = 0; i < N; i++) sumA[i + 1] = sumA[i] + stack1[i]; for (int i = 0; i < M; i++) sumB[i + 1] = sumB[i] + stack2[i]; // Calculate maxNumbers int MaxNumbers = 0; for (int i = 0; i <= N; i++) { // Calculate remaining value of K // after selecting numbers // from 1st stack int remValueOfK = K - sumA[i]; // If rem value of K is less than 0 // continue the loop if (remValueOfK < 0) continue; // Calculate lower bound int lowerBound = lower_bound(sumB, remValueOfK); // If size of lower bound is greater // than self stack size or // value of lower bound element // decrement lowerBound if (lowerBound > M || sumB[lowerBound] > remValueOfK) { lowerBound--; } // Store max possible numbers int books = i + lowerBound; MaxNumbers = Math.max(MaxNumbers, books); } return MaxNumbers; } // Driver Code public static void main(String args[]) { int []stack1 = {60, 90, 120}; int []stack2 = {100, 10, 10, 200}; int K = 130; int N = 3; int M = 4; int ans = maxNumbers(stack1, N, stack2, M, K); System.out.println(ans); } } // This code is contributed by sanjoy_62.
Python3 # Python code for the above approach def lower_bound(a, val): lo = 0 hi = len(a) - 1; while (lo < hi): mid = (lo + (hi - lo) // 2); if (a[mid] < val): lo = mid + 1; else: hi = mid; return lo; # Function to find the # maximum number of elements def maxNumbers(stack1, N, stack2, M, K): # Take prefix of both the stack sumA = [0] * (N + 1) sumB = [0] * (M + 1) for i in range(N): sumA[i + 1] = sumA[i] + stack1[i]; for i in range(M): sumB[i + 1] = sumB[i] + stack2[i]; # Calculate maxNumbers MaxNumbers = 0; for i in range(N + 1): # Calculate remaining value of K # after selecting numbers # from 1st stack remValueOfK = K - sumA[i]; # If rem value of K is less than 0 # continue the loop if (remValueOfK < 0): continue; # Calculate lower bound lowerBound = lower_bound(sumB, remValueOfK); # If size of lower bound is greater # than self stack size or # value of lower bound element # decrement lowerBound if (lowerBound > M or sumB[lowerBound] > remValueOfK): lowerBound -= 1 # Store max possible numbers books = i + lowerBound; MaxNumbers = max(MaxNumbers, books); return MaxNumbers; # Driver code stack1 = [60, 90, 120]; stack2 = [100, 10, 10, 200]; K = 130; N = 3; M = 4; ans = maxNumbers(stack1, N, stack2, M, K); print(ans) # This code is contributed by gfgking
C# // C# code for the above approach using System; class GFG { static int lower_bound(int []a, int val) { int lo = 0, hi = a.Length - 1; while (lo < hi) { int mid = (int)Math.Floor(lo + (double)(hi - lo) / 2); if (a[mid] < val) lo = mid + 1; else hi = mid; } return lo; } // Function to find the // maximum number of elements static int maxNumbers(int []stack1, int N, int []stack2, int M, int K) { // Take prefix of both the stack int []sumA = new int[N + 1]; for(int i = 0; i < N + 1; i++) { sumA[i] = 0; } int []sumB = new int[M + 1]; for(int i = 0; i < M + 1; i++) { sumB[i] = 0; } for (int i = 0; i < N; i++) sumA[i + 1] = sumA[i] + stack1[i]; for (int i = 0; i < M; i++) sumB[i + 1] = sumB[i] + stack2[i]; // Calculate maxNumbers int MaxNumbers = 0; for (int i = 0; i <= N; i++) { // Calculate remaining value of K // after selecting numbers // from 1st stack int remValueOfK = K - sumA[i]; // If rem value of K is less than 0 // continue the loop if (remValueOfK < 0) continue; // Calculate lower bound int lowerBound = lower_bound(sumB, remValueOfK); // If size of lower bound is greater // than self stack size or // value of lower bound element // decrement lowerBound if (lowerBound > M || sumB[lowerBound] > remValueOfK) { lowerBound--; } // Store max possible numbers int books = i + lowerBound; MaxNumbers = Math.Max(MaxNumbers, books); } return MaxNumbers; } // Driver code public static void Main() { int []stack1 = {60, 90, 120}; int []stack2 = {100, 10, 10, 200}; int K = 130; int N = 3; int M = 4; int ans = maxNumbers(stack1, N, stack2, M, K); Console.Write(ans); } } // This code is contributed by Samim Hossain Mondal.
JavaScript <script> // JavaScript code for the above approach function lower_bound(a, val) { let lo = 0, hi = a.length - 1; while (lo < hi) { let mid = Math.floor(lo + (hi - lo) / 2); if (a[mid] < val) lo = mid + 1; else hi = mid; } return lo; } // Function to find the // maximum number of elements function maxNumbers(stack1, N, stack2, M, K) { // Take prefix of both the stack let sumA = new Array(N + 1).fill(0); let sumB = new Array(M + 1).fill(0); for (let i = 0; i < N; i++) sumA[i + 1] = sumA[i] + stack1[i]; for (let i = 0; i < M; i++) sumB[i + 1] = sumB[i] + stack2[i]; // Calculate maxNumbers let MaxNumbers = 0; for (let i = 0; i <= N; i++) { // Calculate remaining value of K // after selecting numbers // from 1st stack let remValueOfK = K - sumA[i]; // If rem value of K is less than 0 // continue the loop if (remValueOfK < 0) continue; // Calculate lower bound let lowerBound = lower_bound(sumB, remValueOfK); // If size of lower bound is greater // than self stack size or // value of lower bound element // decrement lowerBound if (lowerBound > M || sumB[lowerBound] > remValueOfK) { lowerBound--; } // Store max possible numbers let books = i + lowerBound; MaxNumbers = Math.max(MaxNumbers, books); } return MaxNumbers; } // Driver code let stack1 = [60, 90, 120]; let stack2 = [100, 10, 10, 200]; let K = 130; let N = 3; let M = 4; let ans = maxNumbers(stack1, N, stack2, M, K); document.write(ans) // This code is contributed by Potta Lokesh </script>
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Similar Reads
Binary Search on Answer Tutorial with Problems Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
15+ min read
Time Crunch Challenge Geeks for Geeks is organizing a hackathon consisting of N sections, each containing K questions. The duration of the hackathon is H hours. Each participant can determine their speed of solving questions, denoted as S (S = questions-per-hour). During each hour, a participant can choose a section and
10 min read
Find minimum subarray length to reduce frequency Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k. Examples: Input: n = 4, arr[] = {3, 1, 3, 6}, k =
10 min read
Maximize minimum sweetness in cake cutting Given that cake consists of N chunks, whose individual sweetness is represented by the sweetness[] array, the task is to cut the cake into K + 1 pieces to maximize the minimum sweetness. Examples: Input: N = 6, K = 2, sweetness[] = {6, 3, 2, 8, 7, 5}Output: 9Explanation: Divide the cake into [6, 3],
7 min read
Maximize minimum element of an Array using operations Given an array A[] of N integers and two integers X and Y (X ⤠Y), the task is to find the maximum possible value of the minimum element in an array A[] of N integers by adding X to one element and subtracting Y from another element any number of times, where X ⤠Y. Examples: Input: N= 3, A[] = {1,
8 min read
Maximize the minimum element and return it Given an array A[] of size N along with W, K. We can increase W continuous elements by 1 where we are allowed to perform this operation K times, the task is to maximize the minimum element and return the minimum element after operations. Examples: Input: N = 6, K = 2, W = 3, A[] = {2, 2, 2, 2, 1, 1}
8 min read
Find the maximum value of the K-th smallest usage value in Array Given an array arr[] of size N and with integers M, K. You are allowed to perform an operation where you can increase the value of the least element of the array by 1. You are to do this M times. The task is to find the largest possible value for the Kth smallest value among arr[] after M operations
7 min read
Aggressive Cows Given an array stalls[] which denotes the position of a stall and an integer k which denotes the number of aggressive cows. The task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible.Examples: Input: stalls[] = [1, 2, 4, 8, 9], k = 3Output:
15+ min read
Minimum time to complete at least K tasks when everyone rest after each task Given an array arr[] of size n representing the time taken by a person to complete a task. Also, an array restTime[] which denotes the amount of time one person takes to rest after finishing a task. Each person is independent of others i.e. they can work simultaneously on different tasks at the same
8 min read
Maximum count of integers to be chosen from given two stacks having sum at most K Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K. Examples: Input: stack1[ ] = { 60, 90, 120 }stack2[ ] = { 100, 10, 10, 250 }, K = 130Output: 3Explanation: Tak
9 min read