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
  • 相关阅读:
    JS操作JSON总结
    jQuery对select操作
    MS SQL GUID
    QT延时方法
    MySQL 实践
    MySQL 入门教程
    asp.net获取URL和IP地址
    C#-foreach与yield
    C#—序列化(Serialize)和反序列化(NonSerialize)
    Newtonsoft.Json序列化和反序列
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099605.html
Copyright © 2011-2022 走看看