Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 918. Maximum Sum Circular Subarray

Rain Hu

918. Maximum Sum Circular Subarray


一、題目

Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. DP

int maxSubarraySumCircular(vector<int>& nums) {
    int neg_cur = INT_MAX;
    int pos_cur = INT_MIN;
    int total = 0;
    int neg_max = INT_MAX;
    int pos_max = INT_MIN;
    for (int i = 0; i < nums.size(); i++) {
        neg_cur = neg_cur > 0 ? nums[i] : (neg_cur + nums[i]);
        pos_cur = pos_cur < 0 ? nums[i] : (pos_cur + nums[i]);
        neg_max = min(neg_cur, neg_max);                        // 記錄最小子序列
        pos_max = max(pos_cur, pos_max);                        // 記錄最大子序列
        total += nums[i];                                       // 記錄總和
    }
    if (total == neg_max) return pos_max;                       // 當總和等於最小子序列時,因為至少需拿一個元素,特例處理
    return max(pos_max, total - neg_max);                       // 解為最大子序列或總和-最小子序列(環狀)
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 53. Maximum Subarray
Next
[IT] C# Depth Ch.1 與時俱進的語言