zoukankan      html  css  js  c++  java
  • LeetCode

    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,则在后面的数加上现在的和只会比原来的数要小,故舍弃

    DP的思路:
    O(n)就是一维DP。
    假设A(0, i)区间存在k,使得[k, i]区间是以i结尾区间的最大值,定义为Max[i],当求取Max[i+1]时,

    然后从左往右扫描,求取Max数字的最大值即为所求。
     1 class Solution {
     2 public:
     3     int maxSubArray(int A[], int n) {
     4         int ans = 0;
     5         int maxsum = INT_MIN;
     6         
     7         for (int i = 0; i < n; i++)
     8         {
     9             if (ans < 0)
    10                 ans = 0;
    11             ans += A[i];
    12             maxsum = max(ans, maxsum);
    13         }
    14         return maxsum;
    15     }
    16 };
  • 相关阅读:
    php-管理变量
    php-变量的间接引用
    php-eval()
    HTML
    php观
    笔记1
    脚本语言
    Windows Server 2012如何把快捷方式加到启动文件夹中
    VIM的笔记
    mongodb 从3.0 升级到3.2
  • 原文地址:https://www.cnblogs.com/bournet/p/4108624.html
Copyright © 2011-2022 走看看