Reduce N to 0 or less by given X and Y operations
Given three integers N, X, and Y, the task is to check if it is possible to reduce N to 0 or less by the following operations:
- Update N to ⌊N/2⌋ + 10, at most X times
- Update N to N – 10, at most Y times.
Input: N = 100, X = 3, Y = 4
Update N = 100 to ⌊100/2⌋ + 10 = 60.
Update N = 60 to 60 − 10 = 50.
Update N = 50 to ⌊50/2⌋ + 10 = 35.
Update N = 35 to ⌊35/2⌋ + 10 = 27.
Update N = 27 to 27 − 10 = 17.
Update N = 17 to 17 − 10 = 7.
Update N = 7 to 7 − 10 = −3.
Input: N = 50, X = 1, Y = 2
Approach: This problem can be solved based on the following observations:
- Case 1: If ⌊N/2⌋ + 10 >= N, then perform only second operation as the first operation will increase the value N.
- Case 2: If first operation is performed followed by the second operation then the result is:
Operation 1: N = ⌊N/2⌋ + 10
Operation 2: (⌊N/2⌋ + 10) – 10 = ⌊N/2⌋
- The value of N is reduced to (⌊N/2⌋).
- Case 3: If second operation is performed followed by the first operation then the result is:
Operation 2: N = N – 10
Operation 1: ⌊(N – 10)/2⌋ + 10 = (⌊N/2⌋ – 5 + 10) = (⌊N/2⌋ + 5)
- The value of N is reduced to (⌊N/2⌋ + 5).
From the above two observations, if N > N/2 +10, then it can be concluded that, to reduce the value of N to 0 or less, the first operation must be performed before the second operation to decrease the value of N.
Follow the steps below to solve the problem:
- Update the value of N to ⌊N/2⌋ + 10 if N > N/2 + 10 and X > 0.
- Update the value of N to N – 10 at most Y times.
- Check if the updated value of N is less than equal to 0 or not.
- If N ≤ 0, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(X + Y)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.