Largest number upto T formed by combination of As and Bs
Given numbers T, A, and B, the task is to find the greatest number less than equal to T formed by the sum of any combination of A and B (A and B can be used any number of times) along with one special operation that is at any instance sum can be halved (integer division by 2) by its current value at most one time.
Input: T = 8, A = 5, B = 6
Explanation: There are two ways to reach the maximum value 8
- Step 1: Choose 5 to add. the sum becomes 5.
- Step 2: Use special move and halve sum, sum becomes 2 (5÷2 == 2 as this is integer division).
- Step 3: Choose 6 to add, and the sum becomes 8.
- Step 1: Choose 6 to add. the sum becomes 6.
- Step 2: Use a special move and halve sum, sum becomes 3 (6÷2 == 3).
- Step 3: Choose 5 to add, and the sum becomes 8.
8 is the maximum sum possible less than equal to T = 8
Input: T = 11, A = 5, B = 8
There is only one way to reach maximum value11
- Step 1: Choose 5 to add, Sum becomes 5.
- Step 2: Choose again 5 to add, Sum becomes 10.
10 is the maximum sum possible less than equal to T = 11
Naive approach: The basic way to solve the problem is as follows:
The basic way to solve this problem is to generate all possible combinations by using a recursive approach.
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following idea:
Dynamic programming can be used to solve this problem
- dp[i][j] represents maximum sum less than equal to T with j special operations left.
- recurrence relation: dp[i][j] = max(dp[i – A][j], dp[i – B][j]) = dp[i / 2]
it can be observed that the recursive function is called exponential times. That means that some states are called repeatedly. So the idea is to store the value of each state. This can be done using by store the value of a state and whenever the function is called, return the stored value without computing again.
Follow the steps below to solve the problem:
- Create a recursive function that takes i representing the current sum and j representing the number of special operations left to perform.
- Call recursive function for both choosing A into sum and choosing B into sum.
- Create a 2d array of dp[N] with initially filled with -1.
- If the answer for a particular state is computed then save it in dp[i][j].
- If the answer for a particular state is already computed then just return dp[i][j].
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles :
Please Login to comment...