国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Maximum Subarray

2019-11-15 01:08:02
字體:
來源:轉載
供稿:網友
[LeetCode] Maximum Subarray

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;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大余县| 洪湖市| 七台河市| 泸溪县| 化州市| 夏邑县| 齐齐哈尔市| 天镇县| 唐海县| 桑日县| 永定县| 曲靖市| 利辛县| 武定县| 晋州市| 固安县| 红桥区| 盐源县| 荆州市| 灵武市| 通江县| 黄浦区| 浏阳市| 巨鹿县| 林西县| 大足县| 旬邑县| 威宁| 巴楚县| 祥云县| 汉源县| 吴川市| 灵丘县| 南岸区| 亳州市| 涟源市| 宜良县| 内江市| 蓬莱市| 浦江县| 内江市|