給定一個整數陣列 nums ,找到一個具有最大和的連續子陣列(子陣列最少包含一個元素),回傳其最大和,
示例:
輸入: [-2, 1, -3, 4, -1, 2, 1, -5, 4],
輸出: 6
解釋: 連續子陣列 [4,-1,2,1] 的和最大,為 6,
public int maxSubArray(int[] nums) {
int max = nums[0];
int res = 0;
for (int i = 0;i < nums.length; i++){
if(res > 0){
// 如果為正數,則可能存在增益,使得res子列存在更大值
res += nums[i];
}else{
// 如果是負數,則一直都是負數比較
res = nums[i];
}
max = Math.max(max, res);
}
return max;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/47540.html
標籤:其他
