Update Leetcode 题解.md
maxSubArray优化代码,没有必要初始化一个n长度的数组
This commit is contained in:
parent
48c4b15aba
commit
ec2486d3ef
@ -2379,13 +2379,11 @@ class NumArray {
|
||||
|
||||
```java
|
||||
public int maxSubArray(int[] nums) {
|
||||
int n = nums.length;
|
||||
int[] sum = new int[n];
|
||||
sum[0] = nums[0];
|
||||
int max = sum[0];
|
||||
for(int i = 1; i < n; i++){
|
||||
sum[i] = (sum[i-1] > 0 ? sum[i-1] : 0) + nums[i];
|
||||
max = Math.max(max, sum[i]);
|
||||
int max = nums[0];
|
||||
int oldsum = nums[0];
|
||||
for (int i = 1; i < nums.length; i++) {
|
||||
oldsum = (oldsum > 0 ? oldsum: 0) + nums[i];
|
||||
max = Math.max(max, oldsum);
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user