• [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 };
  • 相关阅读:
    PlayerPrefs存储Vector3等结构数据
    Kafka集群部署及測试
    火云开发课堂
    Thinking in Java:容器深入研究
    求int型数据在内存中存储时1的个数
    JAVA 几种多线程的简单实例 Thread Runnable
    Android利用Intent与其它应用交互
    kernel
    Azure DocumentDB 正式发布
    在公有云平台体验开源方案的自动部署
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4734493.html
Copyright © 2020-2023  润新知