【Leetcode】最大子陣列和
阿新 • • 發佈:2022-04-12
採用分治演算法,
陣列區間[left, right], mid = (right + left) / 2
最大子陣列存在於可能的三種情況:
[left, mid], [mid + 1, right], 橫跨前兩個
而第三種情況可以拆成[lb, mid] 和 [mid + 1, ub]的並集
class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.size() == 1) return nums[0]; if (nums.size() == 2) return max(nums[0], nums[1], nums[0] + nums[1]); int left = 0, right = nums.size() - 1, mid = left + (right - left) / 2; int left_max = nums[mid], right_max = 0, cur_left = 0, cur_right = 0; vector<int>left_nums, right_nums; for (int i = mid; i >= 0; --i) { cur_left+= nums[i]; if (cur_left > left_max) left_max = cur_left; left_nums.push_back(nums[i]); } if (mid + 1 <= right) right_max = nums[mid + 1]; for (int i = mid + 1; i <= right; ++i) { cur_right += nums[i]; if (cur_right > right_max) right_max = cur_right; right_nums.push_back(nums[i]); }return max(maxSubArray(left_nums), maxSubArray(right_nums), left_max + right_max); } int max(int a, int b, int c) { int m = a; if (m < b) m = b; if (m < c) m = c; return m; } };