zoukankan      html  css  js  c++  java
  • [LeetCode] Maximum Subarray Sum


    Dynamic Programming

    There is a nice introduction to the DP algorithm in this Wikipedia article. The idea is to maintain a running maximum smax and a current summation sum. When we visit each num in nums, addnum to sum, then update smax if necessary or reset sum to 0 if it becomes negative.

    The code is as follows.

     1 class Solution {
     2 public:
     3     int maxSubArray(vector<int>& nums) {
     4         int sum = 0, smax = INT_MIN;
     5         for (int num : nums) {
     6             sum += num;
     7             if (sum > smax) smax = sum;
     8             if (sum < 0) sum = 0;
     9         }
    10         return smax;
    11     }
    12 };

    Divide and Conquer

    The DC algorithm breaks nums into two halves and find the maximum subarray sum in them recursively. Well, the most tricky part is to handle the case that the maximum subarray may span the two halves. For this case, we use a linear algorithm: starting from the middle element and move to both ends (left and right ends), record the maximum sum we have seen. In this case, the maximum sum is finally equal to the middle element plus the maximum sum of moving leftwards and the maximum sum of moving rightwards.

    Well, the code is just a translation of the above idea.

     1 class Solution {
     2 public:
     3     int maxSubArray(vector<int>& nums) {
     4         int smax = INT_MIN, n = nums.size();
     5         return maxSub(nums, 0, n - 1, smax);
     6     }
     7 private:
     8     int maxSub(vector<int>& nums, int l, int r, int smax) {
     9         if (l > r) return INT_MIN;
    10         int m = l + ((r - l) >> 1);
    11         int lm = maxSub(nums, l, m - 1, smax); // left half
    12         int rm = maxSub(nums, m + 1, r, smax); // right half
    13         int i, sum, ml = 0, mr = 0;
    14         // Move leftwards
    15         for (i = m - 1, sum = 0; i >= l; i--) {
    16             sum += nums[i];
    17             ml = max(sum, ml); 
    18         }
    19         // Move rightwards
    20         for (i = m + 1, sum = 0; i <= r; i++) {
    21             sum += nums[i];
    22             mr = max(sum, mr);
    23         }
    24         return max(smax, max(ml + mr + nums[m], max(lm, rm)));
    25     }
    26 };
  • 相关阅读:
    让Lua支持Linq吧
    游戏提高性能 游戏降帧处理
    Lua BehaviourTree 各节点说明
    AssetsManagerEx 组件使用说明
    CocosStudio文件解析工具CsdAnalysis
    Cocos2dx实现光影效果的两种方式
    C++ 版本的 行为树的简单实现
    Buff系统设计
    SetZOrder 无效
    CClayer ignoreAnchorPointForPosition 参数的作用
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4734493.html
Copyright © 2011-2022 走看看