3919. Minimum Cost to Move Between Indices
Description
You are given an integer array nums where nums is strictly increasing.
For each index x, let closest(x) be the adjacent index y such that abs(nums[x] - nums[y]) is minimized. If both adjacent indices exist and give the same difference, choose the smaller index.
From any index x, you can move in two ways:
- To any index
ywith costabs(nums[x] - nums[y]), or - To
closest(x)with cost 1.
You are also given a 2D integer array queries, where each queries[i] = [li, ri].
For each query, calculate the minimum total cost to move from index li to index ri.
Return an integer array ans, where ans[i] is the answer for the ith query.
The absolute difference between two values x and y is defined as abs(x - y).
Example 1:
Input: nums = [-5,-2,3], queries = [[0,2],[2,0],[1,2]]
Output: [6,2,5]
Explanation:
- The closest indices are
[1, 0, 1]respectively. - For
[0, 2], the path0 → 1 → 2uses a closest move from index 0 to 1 with cost 1 and a move from index 1 to 2 with cost|-2 - 3| = 5, giving total1 + 5 = 6. - For
[2, 0], the path2 → 1 → 0uses two closest moves from index 2 to 1 and from index 1 to 0, each with cost 1, giving total 2. - For
[1, 2], the direct move from index 1 to index 2 has cost|-2 - 3| = 5, which is optimal.
Thus, ans = [6, 2, 5].
Example 2:
Input: nums = [0,2,3,9], queries = [[3,0],[1,2],[2,0]]
Output: [4,1,3]
Explanation:
- The closest indices are
[1, 2, 1, 2]respectively. - For
[3, 0], the path3 → 2 → 1 → 0uses closest moves from index 3 to 2 and from 2 to 1, each with cost 1, and a move from 1 to 0 with cost|2 - 0| = 2, giving total1 + 1 + 2 = 4. - For
[1, 2], the closest move from index 1 to 2 has cost 1. - For
[2, 0], the path2 → 1 → 0uses a closest move from index 2 to 1 with cost 1 and a move from 1 to 0 with cost|2 - 0| = 2, giving total1 + 2 = 3.
Thus, ans = [4, 1, 3].
Constraints:
2 <= nums.length <= 105-109 <= nums[i] <= 109numsis strictly increasing1 <= queries.length <= 105queries[i] = [li, ri]0 <= li, ri < nums.length
Solutions
Solution 1
Thinking
The array is strictly increasing and there are up to \(10^5\) queries, so we cannot simulate each walk on \([l,r]\). The cost of one adjacent step is determined by a local triple of gaps, and the left-to-right rule is not the same as the opposite direction.
Precompute a rightward cost \(c_1\) and a leftward cost \(c_2\) on every adjacent edge, then store their prefix sums \(s_1\) and \(s_2\). A query with \(l<r\) reads \(s_1[r]-s_1[l]\); otherwise it reads \(s_2[l]-s_2[r]\).
Each query is then \(O(1)\) after an \(O(n)\) preprocess.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |