1、动态规划
int max(int a, int b){
return a>b?a:b;
}
int maxSubArray(int* nums, int numsSize){
int dp[numsSize];
int res = nums[0];
dp[0] = nums[0];
for(int i=1; i<numsSize; i++){
dp[i] = max(dp[i-1]+nums[i],nums[i]);
res = max(res,dp[i]);
}
return res;
}
2、贪心算法
int max(int a, int b){
return a>b?a:b;
}
int maxSubArray(int* nums, int numsSize){
int sum;
int res=nums[0];
for(int i=0; i<numsSize; i++){
sum = max(sum+nums[i],nums[i]);
res = max(res,sum);
}
return res;
}
3、运行用时4ms范例
它这里的思想也是用到贪心算法。只要tmp为负数, 那在进行下一次循环前tmp都初始化为0.因为tmp为负数时,加任何数都是会变小的。因此我们不必保存负数。
4、分治法
(补充:这里我在练习分治法时重新刷到这道题,分治法相较于上面的两个算法,相对复杂,但从宏观来说还是很好理解的,且效率是最高的。)
思想如下:
最大子序,要么在左边,要么在右边,有么跨中间。因此只需要把这三种情况的最大子序求出来,在选出最大的就行。
int max(int a, int b,int c){
a = a>b?a:b;
return a>c?a:c;
}
//跨中间时
int crossSub(int *nums, int low,int mid,int high,int max_l, int max_r){
int left=mid,right=mid+1;
int sum_max = nums[left--]+nums[right++];
int sum_l,sum_r;
sum_l = sum_max;
while(left>=low){
sum_l= sum_l + nums[left--];
sum_max = sum_max>sum_l?sum_max:sum_l;
}
sum_r = sum_max;
while(right<=high){
sum_r= sum_r + nums[right++];
sum_max = sum_max>sum_r?sum_max:sum_r;
}
return sum_max;
}
int maxSub(int *nums, int low, int high){
if(low == high)
return nums[low];
int mid = (high + low )/2;
int max_l,max_r,c,max_c;
max_l = maxSub(nums,low,mid);
max_r = maxSub(nums,mid+1,high);
max_c = crossSub(nums,low,mid,high,max_l,max_r);
return max(max_l,max_r,max_c);
}
int maxSubArray(int* nums, int numsSize){
return maxSub(nums,0,numsSize-1);
}