Find the contiguous subarray with the largest sum.
Did not get Accepted on the first try – my coding skills really need improvement. Pay attention to boundary conditions. I feel this code is not great.
Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| class Solution {
public:
int maxSubArray(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int sum = 0;
if(n == 1)
{
return A[0];
}
int * value = new int[n];
if(A[0] <= 0)
value[0] = 0;
else
{
value[0] = A[0];
if(value[0] > sum)
sum = value[0];
}
for(int i = 1;i < n;i++)
{
if(A[i] + value[i-1] > 0)
{
value[i] = A[i] + value[i-1];
if(value[i] > sum)
sum = value[i];
}
else
{
value[i] = 0;
}
}
if(sum == 0)
{
sum = -999999999;
for(int i = 0;i < n;i++)
{
if(A[i] > sum)
sum = A[i];
}
}
return sum;
}
};
|