編程語言:JAVA
題目描述:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解題思路:
這道題題目非常簡單,但是做起來就沒那麼簡單了。博主首先想到的也是唯一想到的方法就是暴力窮舉法,時間複雜度很高O(3),果不其然,提交的時候超時。
Kadane Algorithm主要思想是,假設,數組中前i-1項的和爲sum[i-1],對於第i個數字,則由公式
這個公式的直觀解釋爲:當前i-1個數組的和加上arr[i]還沒有arr[i]大的時候,就不考慮前i-1個數字,從當前數字開始新的計算。
保留一個max保存最大的值,每次都和max比較。
代碼:
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE, curSum = 0;
for (int num : nums) {
curSum = Math.max(curSum + num, num);
res = Math.max(res, curSum);
}
return res;
}
}
解法二:
這道題題目中的提示是要按照分製法來求解的,顯然之前的算法不太符合題目本意。