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瀑布流
    瀑布流懒加载
    js的垃圾回收机制
    TCP三次挥手四次握手
    HTTP与HTTPS的区别
    http报文
    前后端的分离
    express中间件
    vue生命周期钩子函数解读步骤
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099605.html
Copyright © 2011-2022 走看看