leetcode[53]Maximum Subarray

最大连续子序列和,非常经典的dp问题。状态转移方程如下所示:
f[i] = max(f[i-1]+a[i],f[i-1]);
max({f[i]})
分析可以参考一下链接
http://www.tuicool.com/articles/UzmU7jb
http://blog.csdn.net/lanxu_yy/article/details/17527745
http://www.acmerblog.com/leetcode-solution-maximum-subarray-6334.html
代码如下所示

#include<stdio.h>
int max(int a,int b){
        if(a >= b){
                return a ;
        }else{
                return b ;
        }
}
int maxSubArray(int* nums, int numsSize) {
        int sum[numsSize] ;
        sum[0] = nums[0] ;
        for(int i=1;i<numsSize;i++){
                sum[i] = max(sum[i-1]+nums[i],nums[i]) ;
        }
        int max = -10000 ;
        for(int i=0;i<numsSize;i++){
                if(sum[i]>max){
                        max = sum[i] ;
                }
        }
        return max ;
}

int main(){
        int nums[] = {-2,1,-3,4,-1,2,1,-5,4} ;
        int result = maxSubArray(nums,9) ;
        printf("%d\n",result) ;
        return 0 ;
}

你可能感兴趣的:(LeetCode,dp)