File tree 4 files changed +23
-16
lines changed
solution/0000-0099/0053.Maximum Subarray
4 files changed +23
-16
lines changed Original file line number Diff line number Diff line change 19
19
- ` 1 <= arr.length <= 10^5 `
20
20
- ` -100 <= arr[i] <= 100 `
21
21
22
+ <p >注意:本题与主站 53 题相同:<a href =" https://leetcode-cn.com/problems/maximum-subarray/ " >https://leetcode-cn.com/problems/maximum-subarray/</a ></p >
23
+
22
24
## 解法
23
25
26
+ 设 dp[ i] 表示 ` [0..i] ` 中,以 ` nums[i] ` 结尾的最大子数组和,状态转移方程 ` dp[i] = nums[i] + max(dp[i - 1], 0) ` 。
27
+
28
+ 由于 ` dp[i] ` 只与子问题 ` dp[i-1] ` 有关,故可以用一个变量 f 来表示。
29
+
24
30
<!-- tabs:start -->
25
31
26
32
### ** Python3**
27
33
28
34
``` python
29
35
class Solution :
30
36
def maxSubArray (self , nums : List[int ]) -> int :
31
- res = t = nums[0 ]
32
- for i in range (1 , len (nums)):
33
- t = nums[i] + (0 if t < 0 else t)
34
- res = max (res, t)
37
+ n = len (nums)
38
+ res = f = nums[0 ]
39
+ for i in range (1 , n):
40
+ f = nums[i] + max (f, 0 )
41
+ res = max (res, f)
35
42
return res
36
-
37
43
```
38
44
39
45
### ** Java**
40
46
41
47
``` java
42
48
class Solution {
43
49
public int maxSubArray (int [] nums ) {
44
- int res = nums[0 ], t = nums[0 ];
50
+ int res = nums[0 ], f = nums[0 ];
45
51
for (int i = 1 , n = nums. length; i < n; ++ i) {
46
- t = nums[i] + (t < 0 ? 0 : t );
47
- res = Math . max(res, t );
52
+ f = nums[i] + Math . max(f, 0 );
53
+ res = Math . max(res, f );
48
54
}
49
55
return res;
50
56
}
Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int maxSubArray (int [] nums ) {
3
- int res = nums [0 ], t = nums [0 ];
3
+ int res = nums [0 ], f = nums [0 ];
4
4
for (int i = 1 , n = nums .length ; i < n ; ++i ) {
5
- t = nums [i ] + ( t < 0 ? 0 : t );
6
- res = Math .max (res , t );
5
+ f = nums [i ] + Math . max ( f , 0 );
6
+ res = Math .max (res , f );
7
7
}
8
8
return res ;
9
9
}
Original file line number Diff line number Diff line change 1
1
class Solution :
2
2
def maxSubArray (self , nums : List [int ]) -> int :
3
- res = t = nums [0 ]
4
- for i in range (1 , len (nums )):
5
- t = nums [i ] + (0 if t < 0 else t )
6
- res = max (res , t )
3
+ n = len (nums )
4
+ res = f = nums [0 ]
5
+ for i in range (1 , n ):
6
+ f = nums [i ] + max (f , 0 )
7
+ res = max (res , f )
7
8
return res
Original file line number Diff line number Diff line change 22
22
23
23
<!-- 这里可写通用的实现逻辑 -->
24
24
25
- 设 dp[ i] 表示 ` [0..i] ` 中,以 nums[ i] 结尾的最大子数组和,状态转移方程 ` dp[i] = nums[i] + max(dp[i - 1], 0) ` 。
25
+ 设 dp[ i] 表示 ` [0..i] ` 中,以 ` nums[i] ` 结尾的最大子数组和,状态转移方程 ` dp[i] = nums[i] + max(dp[i - 1], 0) ` 。
26
26
27
27
由于 ` dp[i] ` 只与子问题 ` dp[i-1] ` 有关,故可以用一个变量 f 来表示。
28
28
You can’t perform that action at this time.
0 commit comments