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.
這道題呢在題目里的提示tag里就說了要用dynamic PRogramming來做。所以我們先明確一下dynamic programming的定義:
We should ignore the sum of the previous n-1 elements if nth element is greater than the sum.
所以根據定義來說,這道題找subarray的話,如果第N個數大于【它本身和前面N-1個數的總和】的話,我們就可以直接無視前面的N-1個數了。
所以我們可以用兩個Math.max來計算,一個用來檢查是否需要無視前面n-1個數,一邊則把新得出來的算術結果與之前已知的最大結果進行比較。
需要注意的是,因為一般初始max值都是設的是第一個數的值,所以用dynamic programming的時候,loop時我們可以直接從i=1開始。
代碼如下:
public class Solution { public int maxSubArray(int[] nums) { //dynamic programming: //We should ignore the sum of the previous n-1 elements if nth element is greater than the sum." int[] result=new int[nums.length]; result[0]=nums[0]; int max=nums[0]; for(int i=1;i<nums.length;i++){ result[i]=Math.max(nums[i],result[i-1]+nums[i]); max=Math.max(max,result[i]); } return max; }}新聞熱點
疑難解答