LeetCode 53. Maximum Subarray
Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.A subarray is a contiguous part of an array.
To be honest, I have no idea how to solve this problem on my own. I know it has something to do with dynamic programming but I just could not figure out how the state transfer should be implemented. So, I cheated and went to the discussion for answers, and then I found Kadane's algorithm.
It is a rather simple and straightforward algorithm. We first initialize an integer dp array, with dp[i] meaning the maximum sum of a subarray up to the i-th element. To determine what to pass to the array, we simply take the maximum of the following two:
1) the current value in nums, i.e. nums[i]
2) the sum of the current value and the maximum value one element before, i.e. nums[i] + dp[i-1]
To get the maximum value of any subarray, we simply take the maximum in our dp array.
I'll try the explain why the algorithm works:
This algorithm always leaves room for the next element in line, thus allowing the subarray to expand and take in larger elements that are about to come in. But when the next element is too small, i.e. too negative that makes it not worth including it when compared to the element alone, we simply disconnect the subarray. This "discontinuing act" is always true as we would not include subarrays that make our current subarray goes smaller. We are better off starting a new one.
Here's the implementation:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
// dp array reduced to a single variable
// as the it only relies one element before it
int dp = nums[0];
// stores the maximum value of dp
int m = dp;
// loop through the given array
for(int i = 1; i < nums.size(); i++){
// transfer of states and finding maximum
dp = max(nums[i], nums[i] + dp);
m = max(m, dp);
}
// return the maximum value
return m;
}
};
P.S. It is only an easy question. It bodes for more practising. TT