|
| 1 | +/** |
| 2 | + * 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum |
| 3 | + * https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an array of integers arr and an integer target. |
| 7 | + * |
| 8 | + * You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There |
| 9 | + * can be multiple answers so you have to find an answer where the sum of the lengths of the |
| 10 | + * two sub-arrays is minimum. |
| 11 | + * |
| 12 | + * Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you |
| 13 | + * cannot find such two sub-arrays. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[]} arr |
| 18 | + * @param {number} target |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var minSumOfLengths = function(arr, target) { |
| 22 | + const prefixSums = new Map([[0, -1]]); |
| 23 | + let currentSum = 0; |
| 24 | + let minLength = Infinity; |
| 25 | + const minLengths = new Array(arr.length).fill(Infinity); |
| 26 | + let result = Infinity; |
| 27 | + |
| 28 | + for (let i = 0; i < arr.length; i++) { |
| 29 | + currentSum += arr[i]; |
| 30 | + if (prefixSums.has(currentSum - target)) { |
| 31 | + const start = prefixSums.get(currentSum - target); |
| 32 | + const length = i - start; |
| 33 | + minLength = Math.min(minLength, length); |
| 34 | + if (start >= 0 && minLengths[start] !== Infinity) { |
| 35 | + result = Math.min(result, length + minLengths[start]); |
| 36 | + } |
| 37 | + } |
| 38 | + minLengths[i] = minLength; |
| 39 | + prefixSums.set(currentSum, i); |
| 40 | + } |
| 41 | + |
| 42 | + return result === Infinity ? -1 : result; |
| 43 | +}; |
0 commit comments