描述
給定一個整數數組,找到一個具有最大和的子數組,返回其最大和。
思路
一次循環,開始初始化一個sum用于保存和,當這個和為負數時,將其置零。可以理解為當一個子數組的和為負數時,不再參與后續的計算,因為算的結果一定會更小。
代碼
public class Solution {
/*
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
// write your code here
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum < 0) {
sum = 0;
} else {
if (sum > max) {
max = sum;
}
}
}
return max;
}
}