Given two integers N and K, denoting the number of operations allowed and the number that needs to be obtained after performing N operations respectively. Consider a value S, initially 0, the task is to convert S to K by performing the following operations N times in any manner:
- Subtract 1 from S.
- Add P + 1 to S, where P is the number added previously(initially 0).
If it is not possible to convert S to K, print -1. Otherwise, print the number of decrement operations are required to be performed.
Note: S must be positive after every operation performed.
Input: N = 5, K = 4
The order of the N operations performed:
Step 1: Adding 1 to S converts S = 1
Step 2: Adding 2 to S converts S = 3
Step 3: Subtracting 1 from S converts S = 2
Step 4: Adding 3 to S converts S = 5
Step 5: Subtracting 1 from S converts S = 4.
Since S is equal to K after N(= 5) operations, the answer is 2 as 2 decrement operations are performed.
Input: N = 10, K = 3
Naive Approach: The simplest idea is to iterate a loop over the range [1, N] and check for the following conditions:
and i + K = N.
If there exists any value of i from the range [1, N] satisfying the above conditions, then print the value of i. Otherwise, print “-1”.
Time Complexity: O(N), where N is the maximum number of steps allowed.
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Binary Search. Below are the steps:
- Initialize two variables start as 0 and end as N.
- Find the middle index of the above two variables by taking the average of start and end.
- Check if we can have a mid number of steps of Type 1. If yes, then print mid and stop the iteration.
- Else update start or end according to the results we get by checking mid and repeat from step 2.
- If there doesn’t exist any mid satisfying the given condition then print “-1”.
Below is the implementation for the above approach:
Time Complexity: O(log2N), where N is the given steps
Space Complexity: O(1)
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.