Leetcode 53. 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.
分析:
题目要求在数组中找到一个连续的子数组,这个子数组的和最大。
第一个想法是,通过一个result数组来记录直到第i个元素且i必选的最大子数组的和,可以很容易写出状态转移方程如下:
if (result[i - 1] < 0) {
result.push_back(nums[i]);
} else {
result.push_back(result[i - 1] + nums[i]);
}
此时,可以看到,空间复杂度是O(n),时间复杂度也是O(n)。
考虑另外一种思路,Kadane’s algorithm,可以只需要O(1)的空间复杂度和O(n)的时间复杂度。
Kadane’s algorithm的思路就是:
对于当前遍历到的元素,这个元素可以加入到当前的连续子数组,作为最后一个元素,或者,舍弃之前的连续子数组,将当前元素作为新的子数组的第一个元素。
可以写出状态转移方程如下:
max_ending_here = max(nums[i], nums[i] + max_ending_here);
代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_so_far = nums[0], max_ending_here = nums[0];
for (int i = 1; i < nums.size(); i++) {
max_ending_here = max(nums[i], nums[i] + max_ending_here);
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
};
运行结果:
Leetcode 152. Maximum Product Subarray
题目:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
分析:
这道题目是寻找数组中的一个连续子数组,使得这个连续子数组的乘积最大。
乍一看这道题目跟上面求子数组的最大和的题目没什么不同,甚至好像可以直接复用上面的代码。
但是,经过这样的尝试后,发现,并不可以!!!
因为乘法的性质,负负得正,而对于负数,在我们不能知道下一个数时,往往就将负数丢弃了。
经过上面的Kadane’s algorithm的方法的启发,我们可以通过记录直到当前位置的两个数,来获得最大的乘积,首先是需要保存是直到当前(包括当前元素)的最大乘积,以及直到当前(包括当前元素)的最小乘积。因为即使是乘法有负负得正的性质,要想获得最大的乘积,那么负数的数值也需要是最小的。因此可以通过保存最小的乘积来保存。
这样的算法,时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int max_so_far = nums[0], max_ending_here = nums[0];
int min_ending_here = nums[0];
for (int i = 1; i < nums.size(); i++) {
int temp1 = max_ending_here, temp2 = min_ending_here;
max_ending_here = max(nums[i], min_ending_here * nums[i]);
max_ending_here = max(temp1 * nums[i], max_ending_here);
min_ending_here = min(temp1 * nums[i], nums[i]);
min_ending_here = min(temp2 * nums[i], min_ending_here);
max_so_far = max(max_ending_here, max_so_far);
}
return max_so_far;
}
};