https://www.geeksforgeeks.org/minimum-time-to-reach-a-point-with-t-and-t-moves-at-time-t/
Given a positive coordinate ‘X’ and you are at coordinate ‘0’, the task is to find the minimum time required to get to coordinate ‘X’ with the following move :
At time ‘t’, you can either stay at the same position or take a jump of length exactly ‘t’ either to the left or to the right. In other words, you can be at coordinate ‘x – t’, ‘x’ or ‘x + t’ at time ‘t’ where ‘x’ is the current position.
At time ‘t’, you can either stay at the same position or take a jump of length exactly ‘t’ either to the left or to the right. In other words, you can be at coordinate ‘x – t’, ‘x’ or ‘x + t’ at time ‘t’ where ‘x’ is the current position.
Examples:
Input: 9 Output: 4 At time 1, do not jump i.e x = 0 At time 2, jump from x = 0 to x = 2 (x = x + 2) At time 3, jump from x = 2 to x = 5 (x = x + 3) At time 4, jump from x = 5 to x = 9 (x = x + 4) So, minimum required time is 4.
Approach: The following greedy strategy works:
We just find the minimum ‘t’ such that
We just find the minimum ‘t’ such that
1 + 2 + 3 + ... + t >= X
.- If
(t * (t + 1)) / 2 = X
then answer is ‘t’. - Else if
(t * (t + 1)) / 2 > X
, then we find(t * (t + 1)) / 2 – X
and remove this number from the sequence[1, 2, 3, ..., t]
. The resulting sequence sums up to ‘X’.