Skip to content

Commit e25afef

Browse files
committed
325. Maximum Size Subarray Sum Equals k
1 parent 084f4c1 commit e25afef

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

.DS_Store

0 Bytes
Binary file not shown.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Not only Leetcode solutions in Swift.
2121
* [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)
2222
* [229. Majority Element II](https://leetcode.com/problems/majority-element-ii/)
2323
* [259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller)
24+
* [325. Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)
2425
* [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)
2526
* [350. Intersection of Two Arrays II](http://www.jiuzhang.com/solutions/intersection-of-two-arrays-ii/)
2627
* [454. 4Sum II](https://leetcode.com/problems/4sum-ii/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,39 @@ let threeSumSmallerNums = [-2, 0, 1, 3]
761761
let threeSumSmallerTarget = 2
762762
Solution.threeSumSmaller(nums: threeSumSmallerNums, threeSumSmallerTarget)
763763

764+
/**
765+
* 325. Maximum Size Subarray Sum Equals k
766+
* https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
767+
*/
768+
769+
extension Solution {
770+
class func maxSubArrayLen(nums: [Int]?, _ k: Int) -> Int {
771+
guard let nums = nums else { return 0 }
772+
773+
var sum = 0
774+
var res = 0
775+
var m = [Int: Int]()
776+
777+
for (i, num) in nums.enumerated() {
778+
sum += num
779+
if (sum == k) {
780+
res = i + 1
781+
} else if let idx = m[sum - k] {
782+
res = max(res, i - idx)
783+
}
784+
785+
if (m[sum] == nil) {
786+
m[sum] = i
787+
}
788+
}
789+
return res
790+
}
791+
}
792+
793+
// usage
794+
let maxSubArrayLenNums = [1, -1, 5, -2, 3]
795+
Solution.maxSubArrayLen(nums: maxSubArrayLenNums, 3)
796+
764797
/**
765798
* 349. Intersection of Two Arrays
766799
* https://leetcode.com/problems/intersection-of-two-arrays/

0 commit comments

Comments
 (0)