File tree Expand file tree Collapse file tree 4 files changed +23
-16
lines changed
solution/0000-0099/0053.Maximum Subarray Expand file tree Collapse file tree 4 files changed +23
-16
lines changed Original file line number Diff line number Diff line change 1919- ` 1 <= arr.length <= 10^5 `
2020- ` -100 <= arr[i] <= 100 `
2121
22+ <p >注意:本题与主站 53 题相同:<a href =" https://leetcode-cn.com/problems/maximum-subarray/ " >https://leetcode-cn.com/problems/maximum-subarray/</a ></p >
23+
2224## 解法
2325
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+
2430<!-- tabs:start -->
2531
2632### ** Python3**
2733
2834``` python
2935class Solution :
3036 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)
3542 return res
36-
3743```
3844
3945### ** Java**
4046
4147``` java
4248class Solution {
4349 public int maxSubArray (int [] nums ) {
44- int res = nums[0 ], t = nums[0 ];
50+ int res = nums[0 ], f = nums[0 ];
4551 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 );
4854 }
4955 return res;
5056 }
Original file line number Diff line number Diff line change 11class Solution {
22 public int maxSubArray (int [] nums ) {
3- int res = nums [0 ], t = nums [0 ];
3+ int res = nums [0 ], f = nums [0 ];
44 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 );
77 }
88 return res ;
99 }
Original file line number Diff line number Diff line change 11class Solution :
22 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 )
78 return res
Original file line number Diff line number Diff line change 2222
2323<!-- 这里可写通用的实现逻辑 -->
2424
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) ` 。
2626
2727由于 ` dp[i] ` 只与子问题 ` dp[i-1] ` 有关,故可以用一个变量 f 来表示。
2828
You can’t perform that action at this time.
0 commit comments