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.
複製代碼
給定整數數組號,找到具備最大和的相鄰子數組(至少包含一個數字)並返回其和。
例子:
輸入:[2,1,三、四、一、二、一、五、4],
輸出:6
說明:[4,-1,2,1]的和最大= 6。
跟進:
若是您已經找到了O(n)的解決方案,那麼嘗試使用分治方法編寫另外一個解決方案,這種方法更加微妙。數組
本題是找尋最大值,咱們第一想到的方式是遍歷,一個個的加過去,判斷出現的最大值是多少,固然這個不失爲一種方式,可是換個角度想,加上正數確定是愈來愈大的,加上負數是愈來愈小,若是加上一個負數,都比當前值要小了,那麼就沒有必要在加了,能夠把累加值替換爲當前值了,這樣就不須要重頭遍歷判斷了。因此按照這樣子想,是否能夠一次遍歷就解決呢?bash
按照咱們的思路來編輯,代碼以下app
if (nums.length < 1) {
return 0;
}
int max = nums[0];
int sum = max;
for (int i = 1; i < nums.length; i++) {
sum=sum + nums[i] < nums[i]?nums[i]:sum + nums[i];
max=Math.max(sum,max);
}
return max;
複製代碼
時間複雜度: 該方案用了循環m因此f(n)=(n)=n;因此O(f(n))=O(n),即T(n)=O(n)ide
空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);ui
本題的大體解法如上所訴,本題只想到了一種方法,拋開遍歷,只用了這一種方法,可是是否能夠分治法來解決,貌似不太想獲得。spa