You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 0053-maximum-subarray.md
+5-3
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,5 @@
1
1
# 53. Maximum Subarray
2
-
LeetCode problem: [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
2
+
LeetCode problem: [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/){:target="_blank"}
3
3
4
4
## Problem
5
5
> Given an integer array nums, find the subarray with the largest sum, and return its sum.
@@ -12,19 +12,21 @@ Explanation: The subarray [4,-1,2,1] has the largest sum 6.
12
12
```
13
13
14
14
## Thoughts
15
+
* This problem can be solved by using `greedy algorithm`, but here we will use another way.
15
16
* Imagine the size of nums is `i`, let us consider if the same question is applied to the `subarray` of `nums` from index `0` to `i - 1`.
16
17
* The answer is `yes`. Then let us think if the `i - 1`'s answer could impact the answer of `i`.
17
18
* The answer is still `yes`. What would be the impact?
18
-
* For index `i`,
19
+
* For `nums[i]`,
19
20
if the `previous sum` is negative, we can discard it;
20
21
if the `previous sum` is positive, we can add it to the `current sum`.
21
-
* So we can use dynamic programming to solve the problem, but we should use the `current sum` instead of the `largest sum` in the `dp` array because `largest sum` is recorded in the `dp` array.
22
+
* So we can use dynamic programming to solve the problem.
22
23
23
24
### Common steps in dynamic programming
24
25
These five steps are a pattern for solving dynamic programming problems.
25
26
26
27
1. Define the `dp` array
27
28
*`dp[i]` represents the `current sum` at index `i`.
29
+
* We should not define `dp[i]` as the `largest sum` because `largest sum` is recorded in the `current sum` array.
0 commit comments