Problem:
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
.
solution:
#include<iostream>
#include<string>
using namespace std;
int maxSubArray(int* nums, int numsSize);
int main()
{
int a[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
cout << maxSubArray(a, 9) << endl;
getchar();
}
int maxSubArray(int* nums, int numsSize) {
int i, j, max, sum;
max = nums[0];
for (i = 0; i < numsSize; i++)
{
sum = 0;
for (j = i; j < numsSize; j++)
{
sum += nums[j];
if (sum > max) max = sum;
}
}
return max;
}