问题描述:
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
.
解题思路:
该题是给出一个序列,然后让我们找到子序列之和最大的子序列的和。
#include"stdio.h"
int pos;
int maxSubArray(int *nums,int numsSize){
int sum=0;
int res=nums[0];
int i;
for(i=0;i<numsSize;i++){
if(sum<0){
sum=0;
int pos;
int maxSubArray(int *nums,int numsSize){
int sum=0;
int res=nums[0];
int i;
for(i=0;i<numsSize;i++){
if(sum<0){
sum=0;
}
sum+=nums[i];
sum+=nums[i];
if(res<=sum){
res=sum;
pos=i;
}
}
pos=i;
}
}
return res;
}
}
void main(){
int a[9]={-2,1,-3,4,-1,2,1,-5,4};
int max,i,count=0;
int a[9]={-2,1,-3,4,-1,2,1,-5,4};
int max,i,count=0;
max=maxSubArray(a,9);
int sum2=a[pos];
int sum2=a[pos];
for(i=pos-1;i>0;i--)
{
if(sum2<max)
{
{
if(sum2<max)
{
sum2=sum2+a[i];
count++;
}
}
count++;
}
}
for(i=count;i<=pos;i++)
printf("%d,",a[i]);
printf("该子序列之和为该序列中最大,其和为:%d",max);
}
printf("%d,",a[i]);
printf("该子序列之和为该序列中最大,其和为:%d",max);
}