Skip to content

Commit 7b92cb4

Browse files
committed
Add solution #1477
1 parent b6ddeee commit 7b92cb4

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,321 LeetCode solutions in JavaScript
1+
# 1,322 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1129,6 +1129,7 @@
11291129
1473|[Paint House III](./solutions/1473-paint-house-iii.js)|Hard|
11301130
1475|[Final Prices With a Special Discount in a Shop](./solutions/1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy|
11311131
1476|[Subrectangle Queries](./solutions/1476-subrectangle-queries.js)|Medium|
1132+
1477|[Find Two Non-overlapping Sub-arrays Each With Target Sum](./solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js)|Medium|
11321133
1480|[Running Sum of 1d Array](./solutions/1480-running-sum-of-1d-array.js)|Easy|
11331134
1481|[Least Number of Unique Integers after K Removals](./solutions/1481-least-number-of-unique-integers-after-k-removals.js)|Medium|
11341135
1486|[XOR Operation in an Array](./solutions/1486-xor-operation-in-an-array.js)|Easy|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)