[LeetCode] Maximum Subarray 最大子陣列
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
這道題讓我們求最大子陣列之和,並且要我們用兩種方法來解,分別是O(n)的解法,還有用分治法Divide and Conquer Approach,這個解法的時間複雜度是O(nlgn),那我們就先來看O(n)的解法,定義兩個變數res和curSum,其中res儲存最終要返回的結果,即最大的子陣列之和,curSum初始值為0,每遍歷一個數字num,比較curSum + num和num中的較大值存入curSum,然後再把res和curSum中的較大值存入res,以此類推直到遍歷完整個陣列,可得到最大子陣列的值存在res中,程式碼如下:
C++ 解法一:
classSolution { public: int maxSubArray(vector<int>& nums) { int res = INT_MIN, curSum = 0; for (int num : nums) { curSum = max(curSum + num, num); res = max(res, curSum); } return res; } };
Java 解法一:
public classSolution { public int maxSubArray(int[] nums) { int res = Integer.MIN_VALUE, curSum = 0; for (int num : nums) { curSum = Math.max(curSum + num, num); res = Math.max(res, curSum); } return res; } }
題目還要求我們用分治法Divide and Conquer Approach來解,這個分治法的思想就類似於二分搜尋法,我們需要把陣列一分為二,分別找出左邊和右邊的最大子陣列之和,然後還要從中間開始向左右分別掃描,求出的最大值分別和左右兩邊得出的最大值相比較取最大的那一個,程式碼如下:
C++ 解法二:
class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.empty()) return 0; return helper(nums, 0, (int)nums.size() - 1); } int helper(vector<int>& nums, int left, int right) { if (left >= right) return nums[left]; int mid = left + (right - left) / 2; int lmax = helper(nums, left, mid - 1); int rmax = helper(nums, mid + 1, right); int mmax = nums[mid], t = mmax; for (int i = mid - 1; i >= left; --i) { t += nums[i]; mmax = max(mmax, t); } t = mmax; for (int i = mid + 1; i <= right; ++i) { t += nums[i]; mmax = max(mmax, t); } return max(mmax, max(lmax, rmax)); } };
Java 解法二:
public class Solution { public int maxSubArray(int[] nums) { if (nums.length == 0) return 0; return helper(nums, 0, nums.length - 1); } public int helper(int[] nums, int left, int right) { if (left >= right) return nums[left]; int mid = left + (right - left) / 2; int lmax = helper(nums, left, mid - 1); int rmax = helper(nums, mid + 1, right); int mmax = nums[mid], t = mmax; for (int i = mid - 1; i >= left; --i) { t += nums[i]; mmax = Math.max(mmax, t); } t = mmax; for (int i = mid + 1; i <= right; ++i) { t += nums[i]; mmax = Math.max(mmax, t); } return Math.max(mmax, Math.max(lmax, rmax)); } }