zoukankan      html  css  js  c++  java
  • LeetCode-53-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.

    题意:就是求最大字数组和。

    思路:

      DP问题,O(n)内可破

      对于位置arr[0]~arr[i],最大字数组和

              arr[0]                  i==0

      maxSum[i]=  

              max{ maxSum[i-1]+arr[i] , arr[i] }     0<i<arr.length

      具体来说该题没必要采用maxSum数组,用一个变量记住最大字数组和即可。

    Java代码如下:

     1 public class Solution {
     2     public int maxSubArray(int[] nums) {
     3         int max = nums[0],maxEndingHere = nums[0];
     4         for (int i = 1; i < nums.length; i++) {
     5             maxEndingHere = Math.max(maxEndingHere+nums[i],nums[i]);
     6             max = Math.max(maxEndingHere,max);
     7         }
     8         return max;
     9     }
    10 }
  • 相关阅读:
    连通分量板子
    2017年7月17日
    强连通缩点— HDU1827
    马拉车代码
    表达式求值
    Gym-100883F、Gym-101095B状态压缩小结
    矩阵快速幂小结-Hdu2604
    3月27日
    简单移动端自适应轮播图
    上了热搜榜前端工程师面试内幕
  • 原文地址:https://www.cnblogs.com/z941030/p/5608991.html
Copyright © 2011-2022 走看看