zoukankan      html  css  js  c++  java
  • [Leetcode 55] 53 Maximum Subarray

    Problem:

    Analysis:

    Naive solution which compute every possible subarray sum and find the maximum need O(n^3), which is unbearable.

    A O(n) solutoin can be found based on the fact that. If the current sum is greater than or equal to 0, we keep add new element to it. If the current sum is less than 0, we restart compute the sum by assign the current value to it. And every time, we compare it with the max sum to see if we can update the max sum. This is correct because of the following fact: once the current sum less than 0, it will make negative contribution to the following sum procedure. To find the max, the best way is just to throw away these negative part and start from 0. A more pricese explaination requires DP analysis, which I'm not so good at....

    Code:

     1 class Solution {
     2 public:
     3     int maxSubArray(int A[], int n) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int max, cur;
     7         
     8         max = cur = A[0];
     9         for (int i=1; i<n; i++) {
    10             if (cur >= 0) {
    11                 cur += A[i];
    12             } else {
    13                 cur = A[i];
    14             }
    15             
    16             if (max < cur)
    17                 max = cur;
    18         }
    19         
    20         return max;
    21     }
    22 };
    View Code
  • 相关阅读:
    tp框架自带扩展分页类修改样式
    win7获取管理员权限
    Git学习手记(二)
    安卓导出安装包
    浅谈存储过程
    Java宝典
    单例设计模式
    关于Cookie的有关内容
    开辟html5和css3学习随笔(2015-3-2)
    关于面试题
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099605.html
Copyright © 2011-2022 走看看