Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
題目描述:找出數組中連續子數組之和的最大值
思路:這道題看了很久,首先想到的就是暴力破解,那就是三個for循環,然後遍歷數組中的每個子數組找出最大值,
但是這種方法太low了,以前在算法書上印象也看到過類似的題,方法是:
遍歷array,對於每一個數字,我們判斷,(之前的sum + 這個數字) 和 (這個數字) 比大小,如果(這個數字)
自己就比 (之前的sum + 這個數字) 大的話,那麼說明不需要再繼續加了,直接從這個數字,開始繼續,因爲它自己已經比之前的sum都大了。
反過來,如果 (之前的sum + 這個數字)大於 (這個數字)就繼續加下去。
但是這個方法的時間很長
Runtime: 19 ms
Your runtime beats 6.61 % of java submissions.
後來看其他人的答案,發現這個題是真的好,解題的方法很靈活,有很多厲害的方法 比如動態分佈以及分治算法等等,待我看懂後再寫出這個題的其他方法
public int maxSubArray(int[] nums) {
int sum=0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
sum = Math.max(nums[i],nums[i]+sum);
max = Math.max(max,sum);
}
return max;
}
public static void main(String[] args) {
int[] nums = {-2,1,-3,4,-1,2,1,-5,4};
int n = new MaximumSubarray53().maxSubArray(nums);
System.out.println("n = " + n);
}