Skip to content

Commit e64c715

Browse files
committed
Add solution #1546
1 parent 7b69a63 commit e64c715

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,359 LeetCode solutions in JavaScript
1+
# 1,360 LeetCode solutions in JavaScript
22

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

@@ -1181,6 +1181,7 @@
11811181
1542|[Find Longest Awesome Substring](./solutions/1542-find-longest-awesome-substring.js)|Hard|
11821182
1544|[Make The String Great](./solutions/1544-make-the-string-great.js)|Easy|
11831183
1545|[Find Kth Bit in Nth Binary String](./solutions/1545-find-kth-bit-in-nth-binary-string.js)|Medium|
1184+
1546|[Maximum Number of Non-Overlapping Subarrays With Sum Equals Target](./solutions/1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target.js)|Medium|
11841185
1550|[Three Consecutive Odds](./solutions/1550-three-consecutive-odds.js)|Easy|
11851186
1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium|
11861187
1566|[Detect Pattern of Length M Repeated K or More Times](./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
3+
* https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/
4+
* Difficulty: Medium
5+
*
6+
* Given an array nums and an integer target, return the maximum number of non-empty non-overlapping
7+
* subarrays such that the sum of values in each subarray is equal to target.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @param {number} target
13+
* @return {number}
14+
*/
15+
var maxNonOverlapping = function(nums, target) {
16+
const prefixSums = new Map();
17+
let currentSum = 0;
18+
let result = 0;
19+
prefixSums.set(0, 0);
20+
21+
for (let i = 0; i < nums.length; i++) {
22+
currentSum += nums[i];
23+
24+
if (prefixSums.has(currentSum - target)) {
25+
result++;
26+
prefixSums.clear();
27+
prefixSums.set(0, i + 1);
28+
currentSum = 0;
29+
} else {
30+
prefixSums.set(currentSum, i + 1);
31+
}
32+
}
33+
34+
return result;
35+
};

0 commit comments

Comments
 (0)