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 DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Maximum Tip Calculator
Next article icon

Maximum Tip Calculator

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Rahul and Ankit are the only two waiters in the Royal Restaurant. Today, the restaurant received N orders. The amount of tips may differ when handled by different waiters and given as arrays A[] and B[] such that if Rahul takes the ith Order, he would be tipped A[i] rupees, and if Ankit takes this order, the tip would be B[i] rupees.

In order to maximize the total tip value, they decided to distribute the order among themselves. One order will be handled by one person only. Also, due to time constraints, Rahul cannot take more than X orders and Ankit cannot take more than Y orders. It is guaranteed that X + Y is greater than or equal to N, which means that all the orders can be handled by either Rahul or Ankit. The task is to find out the maximum possible amount of total tip money after processing all the orders.

Examples:

Input: N = 5, X = 3, Y = 3, A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}
Output: 21
Explanation:
Step 1: 5 is included from Ankit's array
Step 2: 4 is included from Ankit's array
Step 3: As both of them has same value 3 then choose any one of them
Step 4: 4 is included from Rahul's array
Step 4: 5 is included from Rahul's array
Therefore, the maximum possible amount of total tip money sums up to 21.

Input: N = 7, X = 3, Y = 4, A[] = {8, 7, 15, 19, 16, 16, 18}, B[] = {1, 7, 15, 11, 12, 31, 9}
Output: 110

Naive Approach: The simplest approach is to traverse the given arrays and start traversing both the arrays simultaneously and pick the maximum element among them and reduce the count of X if the element is taken from X else the count of Y. If one of the X or Y becomes 0, traverse other non-zero array and add its value to the maximum profit. As in every step, there is a choice to be made, this is similar to the 0-1 Knapsack Problem, in which decisions are made whether to include or exclude an element.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function that finds the maximum tips // from the given arrays as per the // given conditions int maximumTip(vector<int> &arr1,vector<int> & arr2,                int n, int x, int y) {          // Base Condition     if (n == 0)         return 0;              // If both have non-zero count then     // return max element from both array     if (x != 0 and y != 0)         return max(             arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                                  x - 1, y),             arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x,                                                  y - 1));      // Traverse first array, as y     // count has become 0     if (y == 0)         return arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                                      x - 1, y);                                                          // Traverse 2nd array, as x     // count has become 0     else         return arr2[n - 1] + maximumTip(arr1, arr2, n - 1,                                                   x, y - 1); }  // Drive Code int main() {     int N = 5;     int X = 3;     int Y = 3;          vector<int> A = { 1, 2, 3, 4, 5 };     vector<int> B = { 5, 4, 3, 2, 1 };          // Function Call     cout << (maximumTip(A, B, N, X, Y)); }  // This code is contributed by mohit kumar 29 
Java
/*package whatever //do not write package name here */ import java.io.*;  class GFG {      // Function that finds the maximum tips // from the given arrays as per the // given conditions static int maximumTip(int []arr1,int []arr2,                int n, int x, int y) {          // Base Condition     if (n == 0)         return 0;              // If both have non-zero count then     // return max element from both array     if (x != 0 && y != 0)         return Math.max(             arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                                  x - 1, y),             arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x,                                                  y - 1));      // Traverse first array, as y     // count has become 0     if (y == 0)         return arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                                      x - 1, y);                                                          // Traverse 2nd array, as x     // count has become 0     else         return arr2[n - 1] + maximumTip(arr1, arr2, n - 1,                                                   x, y - 1); }  // Drive Code     public static void main (String[] args) {        int N = 5;     int X = 3;     int Y = 3;          int A[] = { 1, 2, 3, 4, 5 };     int B[] = { 5, 4, 3, 2, 1 };          // Function Call                      System.out.println(maximumTip(A, B, N, X, Y));     } }      // This code is contributed by Potta Lokesh 
Python3
# Python program for the above approach  # Function that finds the maximum tips # from the given arrays as per the # given conditions def maximumTip(arr1, arr2, n, x, y):      # Base Condition     if n == 0:         return 0      # If both have non-zero count then     # return max element from both array     if x != 0 and y != 0:         return max(             arr1[n-1] + maximumTip(arr1, arr2, n - 1, x-1, y),             arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1)             )      # Traverse first array, as y     # count has become 0     if y == 0:         return arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y)      # Traverse 2nd array, as x     # count has become 0     else:         return arr2[n - 1] + maximumTip(arr1, arr2, n-1, x, y-1)   # Drive Code N = 5 X = 3 Y = 3 A = [1, 2, 3, 4, 5] B = [5, 4, 3, 2, 1]  # Function Call print(maximumTip(A, B, N, X, Y)) 
C#
/*package whatever //do not write package name here */ using System; public class GFG {    // Function that finds the maximum tips   // from the given arrays as per the   // given conditions   static int maximumTip(int []arr1,int []arr2,                         int n, int x, int y)   {      // Base Condition     if (n == 0)       return 0;      // If both have non-zero count then     // return max element from both array     if (x != 0 && y != 0)       return Math.Max(       arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                x - 1, y),       arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x,                                y - 1));      // Traverse first array, as y     // count has become 0     if (y == 0)       return arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                                        x - 1, y);      // Traverse 2nd array, as x     // count has become 0     else       return arr2[n - 1] + maximumTip(arr1, arr2, n - 1,                                        x, y - 1);   }    // Drive Code   public static void Main(String[] args) {     int N = 5;     int X = 3;     int Y = 3;      int []A = { 1, 2, 3, 4, 5 };     int []B = { 5, 4, 3, 2, 1 };      // Function Call     Console.WriteLine(maximumTip(A, B, N, X, Y));   } }  // This code is contributed by umadevi9616 
JavaScript
<script>         // JavaScript Program for the above approach          // Function that finds the maximum tips         // from the given arrays as per the         // given conditions         function maximumTip(arr1, arr2, n, x, y) {              // Base Condition             if (n == 0)                 return 0;              // If both have non-zero count then             // return max element from both array             if (x != 0 && y != 0)                 return Math.max(                     arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                         x - 1, y),                     arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x,                         y - 1));              // Traverse first array, as y             // count has become 0             if (y == 0)                 return arr1[n - 1] + maximumTip(arr1, arr2, n - 1,                     x - 1, y);              // Traverse 2nd array, as x             // count has become 0             else                 return arr2[n - 1] + maximumTip(arr1, arr2, n - 1,                     x, y - 1);         }          // Drive Code          let N = 5;         let X = 3;         let Y = 3;          let A = [1, 2, 3, 4, 5];         let B = [5, 4, 3, 2, 1];          // Function Call         document.write(maximumTip(A, B, N, X, Y));       // This code is contributed by Potta Lokesh      </script> 

Output
21

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by using Dynamic Programming and Memoization. If execution is traced for the values of N, X, Y, it can be seen that are there are Overlapping Subproblems. These overlapping subproblems can be computed once and stored and used when the same subproblem is called in the recursive call. Below are the steps:

  • Initialize a Map/Dictionary to store the overlapping subproblems result. The keys of the map will be combined values of N, X, and Y.
  • At each recursive call, check if a given key is present in the map then return the value from the map itself.
  • Else, call the function recursively and store the value in the map and return the stored value.
  • If X and Y are non-zero, recursively call function and take the maximum of the value returned when X is used and when Y is used.
  • If X or Y is zero, recursively call for the non-zero array.
  • After the above recursive calls end, then print the maximum possible amount of tip calculated.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> using namespace std; int dp[1001][101][101]; int rec(int level, int x, int y, int arr1[], int arr2[],         int n) {     if (level == n)         return 0;     if (x == 0 && y == 0)         return 0;     if (x == 0)         return arr2[level]                + rec(level + 1, x, y - 1, arr1, arr2, n);     if (y == 0)         return arr1[level]                + rec(level + 1, x - 1, y, arr1, arr2, n);     if (dp[level][x][y] != -1)         return dp[level][x][y];     int ans = max(rec(level + 1, x - 1, y, arr1, arr2, n)                       + arr1[level],                   rec(level + 1, x, y - 1, arr1, arr2, n)                       + arr2[level]);     return dp[level][x][y] = ans; }  void solve() {     int n = 7, x = 3, y = 4;     int arr1[] = { 8, 7, 15, 19, 16, 16, 18 },         arr2[] = { 1, 7, 15, 11, 12, 31, 9 };     memset(dp, -1, sizeof(dp));     cout << rec(0, x, y, arr1, arr2, n); } int main() {     solve();     return 0; } 
Java
// Java program for the above approach import java.io.*; import java.util.HashMap;  class GFG {      // Function that finds the maximum tips     // from the given arrays as per the     // given conditions     static int maximumTip(int[] arr1, int[] arr2, int n,                           int x, int y,                           HashMap<String, Integer> dd)     {         // Create key of N, X, Y         String key = Integer.toString(n) + "_"                      + Integer.toString(x) + "_"                      + Integer.toString(y);                // Return if the current state is         // already calculated         if (dd.get(key) != null)             return dd.get(key);         // Base Condition         if (n == 0)             return 0;          // If both have non-zero count then store and         // return max element from both array         if (x != 0 && y != 0) {             int temp = Math.max(                 arr1[n - 1]                     + maximumTip(arr1, arr2, n - 1, x - 1,                                  y, dd),                 arr2[n - 1]                     + maximumTip(arr1, arr2, n - 1, x,                                  y - 1, dd));             dd.put(key, temp);             // Return the current state result             return dd.get(key);         }          // if y is zero, only x value         // can be used         if (y == 0) {             int temp = arr1[n - 1]                        + maximumTip(arr1, arr2, n - 1,                                     x - 1, y, dd);             dd.put(key, temp);             // Return the current state result             return dd.get(key);         }          // if x is zero, only y value         // can be used         else {             int temp = arr2[n - 1]                        + maximumTip(arr1, arr2, n - 1, x,                                     y - 1, dd);             dd.put(key, temp);             // Return the current state result             return dd.get(key);         }     }      // Driver Code     public static void main(String[] args)     {         int N = 5;         int X = 3;         int Y = 3;          int A[] = { 1, 2, 3, 4, 5 };         int B[] = { 5, 4, 3, 2, 1 };                // Stores the results of the         // overlapping state         HashMap<String, Integer> dd             = new HashMap<String, Integer>();                // Function Call         System.out.println(maximumTip(A, B, N, X, Y, dd));     } }  // This code is contributed by MuskanKalra1 
Python3
# Python program for the above approach   # Function that finds the maximum tips # from the given arrays as per the # given conditions def maximumTip(arr1, arr2, n, x, y, dd):      # Create key of N, X, Y     key = str(n) + '_' + str(x) + '_' + str(y)      # Return if the current state is     # already calculated     if key in dd:         return dd[key]      # Base Condition     if n == 0:         return 0      # Store and return     if x != 0 and y != 0:         dd[key] = max(             arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd),             arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd)         )          # Return the current state result         return dd[key]      # If y is zero, only x value     # can be used     if y == 0:         dd[key] = arr1[n-1] + maximumTip(arr1, arr2, n-1, x-1, y, dd)          # Return the current state result         return dd[key]      # If x is zero, only y value     # can be used     else:          dd[key] = arr2[n-1] + maximumTip(arr1, arr2, n-1, x, y-1, dd)          # Return the current state result         return dd[key]   # Drive Code N = 5 X = 3 Y = 3 A = [1, 2, 3, 4, 5] B = [5, 4, 3, 2, 1]  # Stores the results of the # overlapping state dd = {}  # Function Call print(maximumTip(A, B, N, X, Y, dd)) 
JavaScript
<script>  // JavaScript program for the above approach // Function that finds the maximum tips // from the given arrays as per the // given conditions  function maximumTip(arr1, arr2, n, x, y, dd) {   // Create key of N, X, Y   key = `${n}_${x}_${y}`;      // Return if the current state is   // already calculated   for (var key in dd) {     return dd[key];   }    // Base Condition   if (n == 0) {     return 0;   }    // Store and return   if (x != 0 && y != 0) {     dd[key] = Math.max(       arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd),       arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd)     );      // Return the current state result     return dd[key];   }    // If y is zero, only x value   // can be used   if (y == 0)    {     dd[key] = arr1[n - 1] + maximumTip(arr1, arr2, n - 1, x - 1, y, dd);          // Return the current state result     return dd[key];   }   // If x is zero, only y value   // can be used   else {     dd[key] = arr2[n - 1] + maximumTip(arr1, arr2, n - 1, x, y - 1, dd);     // Return the current state result     return dd[key];   } }  // Drive Code let N = 5; let X = 3; let Y = 3; let A = [1, 2, 3, 4, 5]; let B = [5, 4, 3, 2, 1];  // Stores the results of the // overlapping state dd = {};  // Function Call document.write(maximumTip(A, B, N, X, Y, dd));  // This code is contributed by rdtank. </script> 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG {  // Function that finds the maximum tips // from the given arrays as per the // given conditions     static int maximumTip(int[] arr1, int[] arr2, int n,                     int x, int y,                     Dictionary<string, int> dd)     {         // Create key of N, X, Y         string key = n + "_"                     + x + "_"                     + y;              // Return if the current state is         // already calculated         if (dd.ContainsKey(key))             return dd[key];         // Base Condition         if (n == 0)             return 0;              // If both have non-zero count then store and         // return max element from both array         if (x != 0 && y != 0) {             int temp = Math.Max(                 arr1[n - 1]                     + maximumTip(arr1, arr2, n - 1, x - 1,                                 y, dd),                 arr2[n - 1]                     + maximumTip(arr1, arr2, n - 1, x,                                 y - 1, dd));             dd[key] = temp;             // Return the current state result             return dd[key];         }              // if y is zero, only x value         // can be used         if (y == 0) {             int temp = arr1[n - 1]                     + maximumTip(arr1, arr2, n - 1,                                     x - 1, y, dd);             dd[key] = temp;             // Return the current state result             return dd[key];         }              // if x is zero, only y value         // can be used         else {             int temp = arr2[n - 1]                     + maximumTip(arr1, arr2, n - 1, x,                                     y - 1, dd);             dd[key] = temp;             // Return the current state result             return dd[key];         }     }      // Driver Code     public static void Main(string[] args)     {         int N = 5;         int X = 3;         int Y = 3;              int[] A = { 1, 2, 3, 4, 5 };         int[] B = { 5, 4, 3, 2, 1 };              // Stores the results of the         // overlapping state         Dictionary<string, int> dd             = new Dictionary<string, int>();              // Function Call         Console.WriteLine(maximumTip(A, B, N, X, Y, dd));     } } 

Output
21

Time Complexity: O(N*X*Y)
Auxiliary Space: O(N*X*Y)


Next Article
Maximum Tip Calculator

C

chantya17
Improve
Article Tags :
  • Dynamic Programming
  • Hash
  • Recursion
  • DSA
  • Arrays
  • Amazon
  • Amazon-Question
  • interview-preparation
  • knapsack
Practice Tags :
  • Amazon
  • Arrays
  • Dynamic Programming
  • Hash
  • Recursion

Similar Reads

    Tracking current Maximum Element in a Stack
    Given a Stack, keep track of the maximum value in it. The maximum value may be the top element of the stack, but once a new element is pushed or an element is popped from the stack, the maximum element will be now from the rest of the elements. Examples: Input : 4 19 7 14 20Output : Max Values in st
    6 min read
    Calculate maximum value using '+' or '*' sign between two numbers in a string
    Given a string of numbers, the task is to find the maximum value from the string, you can add a '+' or '*' sign between any two numbers. Examples: Input : 01231 Output : ((((0 + 1) + 2) * 3) + 1) = 10 In above manner, we get the maximum value i.e. 10 Input : 891 Output :73 As 8*9*1 = 72 and 8*9+1 =
    5 min read
    Maximize array elements upto given number
    Given an array of integers, a number and a maximum value, task is to compute the maximum value that can be obtained from the array elements. Every value on the array traversing from the beginning can be either added to or subtracted from the result obtained from previous index such that at any point
    15+ min read
    Maximum value of an integer for which factorial can be calculated on a machine
    Program to find maximum value of an integer for which factorial can be calculated on a machine, assuming that factorial is stored using basic data type like long long int. The idea is based on that fact that, in most of the machines, when we cross limit of integer, the values becomes negative. C++ /
    5 min read
    Maximum in array which is at-least twice of other elements
    Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1. Examples: Input : arr = {3, 6, 1, 0} Output : 1 Here, 6 is the largest integ
    7 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