Leetcode 53:Maximum Subarray (DP基礎)

題目描述:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

題解:

題目鏈接:https://leetcode.com/problems/maximum-subarray/
最近在複習DP,把這道題用DP再做一遍;題意很簡單,就是求一個和最大的子序列,和LIS(最長上升子序列)有點類似;構造狀態轉移方程:
DP(i)=max(DP(i1)+nums(i),nums(i))DP(i) = max(DP(i-1) + nums(i), nums(i))
DP(i)DP(i):代表以nums(i)nums(i)結尾的序列的最大值。

關於DP可以查看DP基礎
DP解法:

class Solution{
public:
    int maxSubArray(vector<int> &nums){
        int len = nums.size(), dp[len], sum;
        dp[0] = sum = nums[0];
        for(int i=1; i<len; i++){
            dp[i] = max(dp[i-1] + nums[i], nums[i]);
            sum = max(sum, dp[i]);
        }
        return sum;
    }
};

這道題的解法有很多:也可以使用Kadane's algorithm,其實和DP的思路有點像了。
理解此算法的關鍵在於:

  • 先將問題進行拆分, 指定數組中某一個元素 A[i],作爲最大子數列的末尾元素時, 能找到的最大子數列的求和值是多少。
  • A[i] 作爲末尾元素時能找到的最大子數列 必然爲A[i] 本身,或是 A[i-1] 作爲末尾元素時能找到的最大子數列加上 A[i]。
int maxSubArray(vector<int>& nums) {
        int curSum, maxSum;
        curSum = maxSum = nums[0];
        for(int i=1; i < nums.size(); i++){
            curSum = max(nums[i], curSum + nums[i]);
            maxSum = max(curSum, maxSum);
        }
        return maxSum;
    }

分治算法:

// Divide and Conquer 分治算法,求每個部分的最大值
    int maxSubArray(vector<int>& nums) {
        maxSub(nums, 0, nums.size()-1);
    }

    int maxSub(vector<int>& nums, int l, int r){
        if(l > r){
            return INT_MIN;
        }
        int m = l + (r - l)/2;
        int lmax = maxSub(nums, l, m-1);
        int rmax = maxSub(nums, m+1, r);
        int ml = 0, mr = 0;
        for(int i = m-1, sum = 0; i >= l; i--){
            sum += nums[i];
            ml = max(ml, sum);
        }
        for(int i = m+1, sum = 0; i <= r; i++){
            sum += nums[i];
            mr = max(mr, sum);
        }
        return max(max(lmax, rmax), ml + mr + nums[m]);
    }

更多代碼可以查看github

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章