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 = 120Input: 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++ 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 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. |
# 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# 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. |
<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>
|
3
Time Complexity: O(N * logN)
Auxiliary Space: O(N)