|
1 | 1 | E |
2 | 2 | 1525331164 |
3 | | -tags: DP, Sequence DP, Array, Divide and Conquer, DFS, PreSum |
| 3 | +tags: DP, Sequence DP, Array, Divide and Conquer, DFS, PreSum, Subarray |
4 | 4 | time: O(n) |
5 | 5 | space: O(n), O(1) rolling array |
6 | 6 |
|
7 | | -给一串数组, 找数组中间 subarray 数字之和的最大值 |
| 7 | +给一串数组, unsorted, can have negative/positive num. 找数组中间 subarray 数字之和的最大值 |
8 | 8 |
|
9 | 9 | #### Sequence DP |
10 | 10 | - dp[i]: 前i个element,包括 last element (i-1), 可能组成的 subarray 的最大sum. |
@@ -58,6 +58,19 @@ If you have figured out the O(n) solution, |
58 | 58 |
|
59 | 59 | */ |
60 | 60 |
|
| 61 | +// Despte the detailed dp[] solution, we have the light version: |
| 62 | +public class Solution { |
| 63 | + public int maxSubArray(int[] nums) { |
| 64 | + if (nums == null || nums.length == 0) return Integer.MIN_VALUE; |
| 65 | + int preMaxSum = 0, max = Integer.MIN_VALUE; |
| 66 | + for (int num : nums) { |
| 67 | + preMaxSum = Math.max(num, preMaxSum + num); |
| 68 | + max = Math.max(max, preMaxSum); |
| 69 | + } |
| 70 | + return max; |
| 71 | + } |
| 72 | +} |
| 73 | + |
61 | 74 | /* |
62 | 75 | Thoughts: |
63 | 76 | sequence dp |
@@ -106,6 +119,8 @@ public int maxSubArray(int[] nums) { |
106 | 119 | } |
107 | 120 | } |
108 | 121 |
|
| 122 | + |
| 123 | + |
109 | 124 | // checking dp[i-1] >= 0. Same as Math.max(dp[i - 1] + nums[i - 1], nums[i - 1]); |
110 | 125 | class Solution { |
111 | 126 | public int maxSubArray(int[] nums) { |
|
0 commit comments