3660. Jump Game IX
Description
You are given an integer array nums.
From any index i, you can jump to another index j under the following rules:
- Jump to index
jwherej > iis allowed only ifnums[j] < nums[i]. - Jump to index
jwherej < iis allowed only ifnums[j] > nums[i].
For each index i, find the maximum value in nums that can be reached by following any sequence of valid jumps starting at i.
Return an array ans where ans[i] is the maximum value reachable starting from index i.
Example 1:
Input: nums = [2,1,3]
Output: [2,2,3]
Explanation:
- For
i = 0: No jump increases the value. - For
i = 1: Jump toj = 0asnums[j] = 2is greater thannums[i]. - For
i = 2: Sincenums[2] = 3is the maximum value innums, no jump increases the value.
Thus, ans = [2, 2, 3].
Example 2:
Input: nums = [2,3,1]
Output: [3,3,3]
Explanation:
- For
i = 0: Jump forward toj = 2asnums[j] = 1is less thannums[i] = 2, then fromi = 2jump toj = 1asnums[j] = 3is greater thannums[2]. - For
i = 1: Sincenums[1] = 3is the maximum value innums, no jump increases the value. - For
i = 2: Jump toj = 1asnums[j] = 3is greater thannums[2] = 1.
Thus, ans = [3, 3, 3].
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109
Solutions
Solution: Prefix Sum
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} nums
* @return {number[]}
*/
const maxValue = function (nums) {
const n = nums.length;
const prefixMax = Array.from({ length: n }, () => 0);
const result = Array.from({ length: n }, () => -1);
let suffixMin = Number.MAX_SAFE_INTEGER;
prefixMax[0] = nums[0];
for (let index = 1; index < n; index++) {
prefixMax[index] = Math.max(nums[index], prefixMax[index - 1]);
}
for (let index = n - 1; index >= 0; index--) {
const num = nums[index];
if (prefixMax[index] > suffixMin) {
result[index] = result[index + 1];
} else {
result[index] = prefixMax[index];
}
suffixMin = Math.min(num, suffixMin);
}
return result;
};