zoukankan      html  css  js  c++  java
  • Maximum Subarray

    It's obvious an DP problem.

    Let's define:

    $dp[i] := $ the maximum sum of subarray in the first $i$ elements.

    From the base point, the optimal subarray may contain element $A[i]$ or not.

    1. optimal subarray without $A[i]$, so $dp[i] = dp[i-1]$.
    2. optimal subarray ending with $A[i]$.

    There're some subtle issues about the second situation. In order to get the second case, we need to know the optimal solution of array ending with $A[i-1]$.

    So, we have to define another dp table:

    $End[i] := $ the maximum sum of subarray ending with $A[i]$.

    Obviously, the $End$ array satisfies:

    End[i] = max(End[i-1] + A[i], A[i]);
    

     In fact, we can simplify as

    End[i] = (End[i-1] > 0) ? End[i-1] + A[i] : A[i];
    

    As both $dp[i]$ and $End[i]$ only relate the previous step, we can use a variable instead of an array to store the result.

    end = (end > 0) ? end + A[i] : A[i];
    dp = max(dp, end); 
    

    Of course, at the initial stage, we consider only one element $A[0]$, thus, we can initialize $dp, end$ as: 

    dp = end = A[0];
    

    The complete code is:

    class Solution {
    public:
        int maxSubArray(int A[], int n) {
            int dp = A[0];
            int end = dp;
            
            for(int i = 1; i < n; ++i){
                end = end > 0 ? end + A[i] : A[i];
                dp = dp > end ? dp : end;
            }
            
            return dp;
        }
    };
    
  • 相关阅读:
    POJ 2752 Seek the Name, Seek the Fame
    POJ 2406 Power Strings
    对闭包的理解(closure)
    HDU
    Python字典遍历的几种方法
    面向对象的六大原则
    Android添加代码检查权限
    Android请求网络权限
    android广播接收器BroadcastReceiver
    Android中SQLite下 Cursor的使用。
  • 原文地址:https://www.cnblogs.com/kid551/p/4153428.html
Copyright © 2011-2022 走看看