public int maxSubArray(int[] nums) {
int ans=nums[0];
int max=0;
for (int num : nums) {
if (max>0){
max=max+num;
}else {
max=num;
}
ans=Math.max(max,ans);
}
return ans;
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int maxSubArray(int* nums, int numsSize) {
int sum = 0;
int max = nums[0];
for (int i = 0; i<numsSize; i++)
{
if (sum>0)
{
sum += nums[i];//只有sum大于0 加上一个数才有可能继续增大
}
if (sum <= 0)
{
sum = nums[i];//sum小于0 就让它等于第i位
}
if (sum>max)
{
max = sum;
}
}
return max;
}
int main()
{
int num[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
int len = sizeof(num) / sizeof(int);
int a = maxSubArray(num, len);
printf("%d\n", a);
system("pause");
return 0;
}