From subarray problems to Kadane and applications
algorithmLet’s start with a problem (src: leetcode#53)
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Constraints:
・ 1 <= nums.length <= 1e5
・ -1e4 <= nums[i] <= 1e4
Since subarray means to a contiguous non-empty sequence of elements within an array. It’s easy to find the trivial solution where we try to calculate all possible subarray.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = INT_MIN;
for (int l = 0; l < nums.size(); ++l) {
for (int r = l; r < nums.size(); ++r) {
int sum = 0;
for (int i = l; i <= r; i++) sum += nums[i];
ans = max(ans, sum);
}
}
return ans;
}
};
The time complexity for this solution is $O(n^{3})$ which clearly impossible to be an AC solution. Then how to update that?
Read more...