Last active
March 30, 2024 13:15
-
-
Save carefree-ladka/ae073d7e7375f77d7ac719c443d5799d to your computer and use it in GitHub Desktop.
SlidingWindow MinSumSubArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const nums = [3, 5, 2, 1, 7] | |
| const getMinSum = (nums, k) => { | |
| let min = Number.MAX_VALUE | |
| let curr = 0 | |
| let start = 0 | |
| let end = 0 | |
| for (let windowEnd = 0; windowEnd < nums.length; windowEnd++) { | |
| curr += nums[windowEnd] | |
| if (windowEnd >= k - 1) { | |
| if (curr < min) { | |
| min = curr | |
| start = windowEnd - k + 1 | |
| end = windowEnd | |
| } | |
| curr -= nums[windowEnd - k + 1] | |
| } | |
| } | |
| return { min, start, end, subarray: nums.slice(start, end + 1) } | |
| } | |
| console.log(getMinSum(nums, 2)); | |
| //{ min: 3, start: 2, end: 3, subarray: [ 2, 1 ] } | |
| //or another version | |
| const maxSubArr = (nums = [], K=2) => { | |
| let max = -Infinity | |
| let left = 0 | |
| let curr=0 | |
| for (let i = 0; i < nums.length; i++){ | |
| curr += nums[i] | |
| if (i - left + 1 === K) { | |
| max = Math.max(max, curr) | |
| curr -= nums[left++] | |
| } | |
| } | |
| return max | |
| } | |
| const nums = [3, 5, 2, 1, 7] | |
| console.log(maxSubArr(nums)); //8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment