Skip to content

Commit ea30fb9

Browse files
authored
JeongAh - Solve leetcode 53.Maximum Subarray (#79)
* Solve leetcode 53.Maximum Subarray * Fix mistake in the example
1 parent 6c30991 commit ea30fb9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/description/)
2+
3+
## Problem Analysis
4+
Some numbers will increase the sum while others won't. More importantly, certain numbers may exceed the current sum on their own. In such cases, the sum should just restart from this large number. Moreover, multiple such occurrences may arise within an array.
5+
6+
## Code
7+
8+
```python
9+
class Solution:
10+
def maxSubArray(self, nums: List[int]) -> int:
11+
cur_sum = 0
12+
max_sum = -inf
13+
14+
for num in nums:
15+
cur_sum += num
16+
17+
if num > cur_sum:
18+
cur_sum = num
19+
20+
max_sum = max(max_sum, cur_sum)
21+
22+
return max_sum
23+
```
24+
25+
## Code Analysis
26+
`cur_sum` is reset anytime there is a number that is greater the current total. Ohterwise, it keeps adding numbers whether they add up the total or not.
27+
So `max_sum` should keep track of the maximum sum that we have encountered so far.
28+
29+
<pre>
30+
[2 -1 -3 4 -1 2 1 -7 4 1 3]
31+
2 1 -2 (2)
32+
4 3 5 6 -1 (3) 4 (num) > 2 (cur_sum)
33+
4 1 3 4 (num) > 3 (cur_sum)
34+
</pre>

0 commit comments

Comments
 (0)