连续子数组-209

// 209(连续子数组)
// time: O(n)
function minSubArrayLen(s, nums) {
  let l = 0, r = -1; // nums [l..r] 滑动窗口
  let sum = 0
  let res = nums.length + 1
  while (l < nums.length) {
    if (r + 1 < nums.length && sum < s) {
      sum += nums[++r]
    } else {
      sum -= nums[l++]
    }
    if (sum >= s) {
      res = Math.min(res, r - l + 1)
    }
  }
  if (res === nums.length + 1) {
    return 0
  }
  return res
}

const r = minSubArrayLen(8, [1, 2, 3, 4, 8, 5])
// console.log(r)

function maxSubArrayLen(nums) {
  let l = 0, r = 0
  let maxLength = 0
  let max = 0
  while (r < nums.length) {
    // console.log(r)
    if (nums[r] >= max) {
      max = nums[r]
      if (r === nums.length - 1) {
        maxLength = Math.max(maxLength, r - l + 1)
        return maxLength
      }
    } else {
      maxLength = Math.max(maxLength, r - l)
      l = r
      max = nums[l]
    }
    r++
  }
  return maxLength
}

const m = maxSubArrayLen([2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 3, 4, 4, 5])
console.log(m)

你可能感兴趣的:(连续子数组-209)