Given two integers N and B, the task is to print the maximum index in an array that can be reached, starting from the 0th index, in N steps without placing itself at index B at any point, where in every ith step, pointer can move i indices to the right.
Input: N = 4, B = 6
Explanation: Following sequence of moves maximizes the index that can be reached.
- Step 1: Initially, pos = 0. Remain in the same position.
- Step 2: Move 2 indices to the right. Therefore, current position = 0 + 2 = 2.
- Step 3: Move 3 indices to the right. Therefore, current position = 2 + 3 = 5.
- Step 4: Move 4 indices to the right. Therefore, current position = 5 + 4 = 9.
Input: N = 2, B = 2
Naive Approach: Refer to the previous post for the simplest approach to solve the problem.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The most optimal idea to solve the problem is based on the following observations:
- If observed carefully, the answer is either the sequence from the arithmetic sum of steps or that of the arithmetic sum of steps – 1.
- This is because, the highest possible number without considering B, is reachable by not waiting (which would give the arithmetic sum).
- But if B is a part of that sequence, then waiting at 0 in the first steps ensures that the sequence does not intersect with the sequence obtained without waiting (as it is always 1 behind).
- Any other sequence (i.e waiting at any other point once or more number of times) will always yield a smaller maximum reachable index.
Follow the steps below to solve the problem:
- Initialize two pointers i = 0 and j = 1.
- Initialize a variable, say sum, to store the sum of first N natural numbers, i.e. N * (N + 1) / 2.
- Initialize a variable, say cnt = 0 and another variable, say flag = false.
- Iterate until cnt is less than N.
- Increment i with j.
- Increment j.
- Increment cnt.
- If at any iteration, i is equal to B, set flag = true and break out of the loop.
- If flag is false, then print sum. Otherwise, print sum – 1.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.