【LeetCode】53. Maximum Subarray

来源:互联网 发布:mac系统机器码怎么查看 编辑:程序博客网 时间:2024/06/18 06:39

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.

      题目大意为在一个字符串中找出一个子串,这个子串要满足其中所有数字相加为所有子串中的最大值。解题思路 从开始处累加,记录下当前最大值,如果前一次累加结果为负值,则直接将之前的累加结果置为零(加上一个负值必然会变小,所以直接去除),一直循环到末尾,就可找出最大值,代码如下:

    /**     * 累加,算出当前结果和最大值     * 只要前面的结果为负数,直接去除(通过将结果置为0)。     */     public int maxSubArray(int[] nums) {        int maxSoFar = Integer.MIN_VALUE;  //初始时和最小值比较        int maxEndingHere = 0;          for(int i=0;i<nums.length;i++) {              if (maxEndingHere<0) {//只要前面的结果为负数,直接去除                  maxEndingHere = 0;              }              maxEndingHere += nums[i];              maxSoFar = Math.max(maxSoFar, maxEndingHere);  //记录下当前最大值        }          return maxSoFar;      }



0 0
原创粉丝点击