Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum count of integers to be chosen from given two stacks having sum at most K
Next article icon

Maximum count of integers to be chosen from given two stacks having sum at most K

Last Updated : 08 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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> 

Output
3

Time Complexity: O(N * logN)
Auxiliary Space: O(N) 


Next Article
Maximum count of integers to be chosen from given two stacks having sum at most K

H

hrithikgarg03188
Improve
Article Tags :
  • Misc
  • Stack
  • Greedy
  • Searching
  • Mathematical
  • DSA
  • Arrays
  • Binary Search
  • prefix-sum
Practice Tags :
  • Arrays
  • Binary Search
  • Greedy
  • Mathematical
  • Misc
  • prefix-sum
  • Searching
  • Stack

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences