1.描述
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.
2.分析
简单的动态规划问题。
3.代码
int maxSubArray(int* nums, int numsSize) {
if (NULL == nums) exit(0);
if (1 == numsSize) return nums[0];
int *dp = (int*)malloc(sizeof(int) * numsSize);
if (NULL == dp) exit(0);
int maxSum = dp[0]=nums[0];
for (unsigned int i = 1; i < numsSize; ++i) {
dp[i] = dp[i-1] > 0 ? dp[i-1] + nums[i] : nums[i];
if (dp[i] > maxSum) maxSum = dp[i];
}
if (dp) {
free(dp);
dp = NULL;
}
return maxSum;
}
网友评论