-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdynamicprogramming1.cpp
58 lines (46 loc) · 1.48 KB
/
dynamicprogramming1.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
47
48
49
50
51
52
53
54
55
56
57
58
// {"category": "DP", "notes": "Find contiguous subarray within array"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Find the contiguous subarray within an array (containing at least one
// number) which has the largest sum.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
int LargestSumInSubarray(int array[], int length)
{
if (length <= 0)
{
return 0;
}
int largestSum = array[0];
int currentSum = array[0];
for (int i = 1; i < length; i++)
{
currentSum = max(currentSum + array[i], array[i]);
largestSum = max(largestSum, currentSum);
}
return largestSum;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
int array1[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
cout << LargestSumInSubarray(array1, ARRAYSIZE(array1)) << endl;
int array2[] = { -2, -1, -3, -4, -1, -2, -1, -5, -4 };
cout << LargestSumInSubarray(array2, ARRAYSIZE(array2)) << endl;
return 0;
}