Skip to content

Commit cda4e6e

Browse files
committed
solve problem Maximum Subarray
1 parent 2ef80ec commit cda4e6e

File tree

5 files changed

+56
-0
lines changed

5 files changed

+56
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ All solutions will be accepted!
143143
|387|[First Unique Character In A String](https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/)|[java/py/js](./algorithms/FirstUniqueCharacterInAString)|Easy|
144144
|628|[Maximum Product Of Three Numbers](https://leetcode-cn.com/problems/maximum-product-of-three-numbers/description/)|[java/py/js](./algorithms/MaximumProductOfThreeNumbers)|Easy|
145145
|724|[Find Pivot Index](https://leetcode-cn.com/problems/find-pivot-index/description/)|[java/py/js](./algorithms/FindPivotIndex)|Easy|
146+
|53|[Maximum Subarray](https://leetcode-cn.com/problems/maximum-subarray/description/)|[java/py/js](./algorithms/MaximumSubarray)|Easy|
146147

147148
# Database
148149
|#|Title|Solution|Difficulty|

algorithms/MaximumSubarray/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Maximum Subarray
2+
This problem is easy to solve, but how to use ***Divide and Conquer*** to solve it
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int maxSubArray(int[] nums) {
3+
int maxSum = Integer.MIN_VALUE,
4+
curSum = Integer.MIN_VALUE;
5+
6+
for (int num : nums) {
7+
if (curSum >= 0 && curSum + num >= 0) {
8+
curSum += num;
9+
} else {
10+
curSum = num;
11+
}
12+
maxSum = Math.max(maxSum, curSum);
13+
}
14+
15+
return maxSum;
16+
}
17+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var maxSubArray = function(nums) {
6+
let maxSum = Number.MIN_SAFE_INTEGER,
7+
curSum = Number.MIN_SAFE_INTEGER
8+
9+
nums.forEach(num => {
10+
if (curSum >= 0 && curSum + num >= 0) {
11+
curSum += num
12+
} else {
13+
curSum = num
14+
}
15+
16+
maxSum = Math.max(maxSum, curSum)
17+
})
18+
19+
return maxSum
20+
};
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution(object):
2+
def maxSubArray(self, nums):
3+
"""
4+
:type nums: List[int]
5+
:rtype: int
6+
"""
7+
max_sum = - sys.maxint
8+
cur_sum = - sys.maxint
9+
10+
for num in nums:
11+
if cur_sum >= 0 and cur_sum + num >= 0:
12+
cur_sum += num
13+
else:
14+
cur_sum = num
15+
max_sum = max(max_sum, cur_sum)
16+
return max_sum

0 commit comments

Comments
 (0)