-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum_subarray.cpp
46 lines (37 loc) · 939 Bytes
/
maximum_subarray.cpp
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
44
45
46
// https://oj.leetcode.com/problems/maximum-subarray/
// Date: Nov 12, 2014
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxSubArray(int A[], int n)
{
// B[i] = max sum of subarray starting from i'th position
// solved in O(n) using dynamic programming
vector<int> B(A,A+n);
int maxSum = B[n-1];
for (int i = n-2; i >= 0; --i)
{
if (B[i+1] > 0)
{
B[i] += B[i+1];
}
if (B[i] > maxSum)
{
maxSum = B[i];
}
}
return maxSum;
}
};
int main(int argc, char* argv[])
{
int A[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
Solution sln;
int maxSum = sln.maxSubArray(A, sizeof(A)/sizeof(A[0]));
return 0;
}
/*
http://stackoverflow.com/questions/20721294/size-of-int-and-sizeof-int-pointer-on-a-64-bit-machine
*/