Find All Good Indices - Dynamic Programming [JS]

Description 

Solution: Dynamic Programming

Compare adjacent numbers and populate left and right, where
left[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

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]