Find All Good Indices - Dynamic Programming [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Dynamic Programming
Compare adjacent numbers and populate left
and right
, whereleft[i] = length of non-increasing subarray ending at index i
right[i] = length of non-decreasing subarray starting at index i
Good indices have left[i - 1] >= k
and right[i + 1] >= k
.
Time Complexity: O(n)
272ms
Space Complexity: O(n)
62.6MB
var goodIndices = function(nums, k) {
let n = nums.length, left = Array(n).fill(1);
for (let i = 1; i < n; i++) {
if (nums[i] <= nums[i - 1]) {
left[i] += left[i - 1];
}
}
let right = Array(n).fill(1);
for (let i = n - 2; i >= 0; i--) {
if (nums[i] <= nums[i + 1]) {
right[i] += right[i + 1];
}
}
let goodIndices = [];
for (let i = k; i < n - k; i++) {
if (left[i - 1] >= k && right[i + 1] >= k) {
goodIndices.push(i);
}
}
return goodIndices;
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment