Find Minimum Time
In the context of an Amazon gaming product involving a snake and apples on a number line, the product simulates a set of unique coordinates representing the positions of the apples. The array named position of size n holds these unique integers, each denoting the coordinate of the nth apple.
The snake, starting at the origin (0 coordinate), decides to consume some of the apples. The snake can move left and right along the line at a constant speed of 1 unit/sec, allowing it to transition from a coordinate x to y (or y to x) in |y - x| seconds. Additionally, the snake can instantly eat an apple when it occupies the same coordinate as the apple.
Given an integer k and the array position, Determine the minimum time required for the snake to consume at least k apples.
Complete the function findMinimumTime in the editor below.
findMinimumTime has the following parameters:
- 1.
int n: the minimum number of apples the snake needs to eat - 2.
int k - 3.
int position[n]: an array of integers denoting the coordinates of the apples on the number line.
Returns
int: the minimum time required for the snake to eat at least k apples.
π³π ππΈ Much appreciated, HxyJxy and spike!ππ
1Example 1
It is optimal to choose the following way:
Time taken will be 5 + 5 + 30 = 40 seconds. It can be shown that it is not possible for the snake to eat all the apples in less than 40 seconds. Hence, the answer is 40.
Constraints
Limits and guarantees your solution can rely on.
1 β€ n β€ 10^51 <= k <= n| position[i]| <= 10^8 OR β108 β€ position[i] β€ 108position consists of distinct integers.