LeetCode 53. Maximum Subarray

53. Maximum Subarray

Difficulty: Medium

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.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

典型的 DP ,解题时间复杂度 O(n)

递推方程

curr(i) = max{curr(i-1), 0} + arr[i]

if  curr(i) > ret    
then    ret = curr(i)

解题代码

int maxSubArray(int* nums, int numsSize) {
	int curr = 0;
	int ret = nums[0];

	for (int i = 0; i < numsSize; i++) {
		if (curr > 0) {
			curr += nums[i];
		} else {
			curr = nums[i];
		}

		if (curr > ret) {
			ret = curr;
		}
	}

	return ret;
}

cost : 4ms

原文地址:https://www.cnblogs.com/fengyubo/p/5724293.html