-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathconstant_space_bottom_up.cpp
70 lines (53 loc) · 1.33 KB
/
constant_space_bottom_up.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
59
60
61
62
63
64
65
66
67
68
69
70
// Note: an env capable of running cpp is required to execute this.
/*
Pseudocode
-----------
f(array)
n := array size
define three ints i_0, i_1, i_2
// initialize the 3 variables just like
// we did for our dp array
i_1 := array[n-1]
i_2 := 0
// this is just to handle the case where the loop
// doesn't even run for a single iteration -- when
// the array has a single element.
i_0 := i_1
// run the loop, updating the variables similar
// to the array implementation.
for(i = n-2 -> 0)
i_0 := max(array[i] + i_2, i_1)
i_2 := i_1
i_1 := i_0
return i_0
*/
#include <iostream.h>
#include <std/c++.h>
using namespace as std;
int main()
{
vector <int> array = {5, 10, 100, 10, 5}
cout << f(array) << endl;
return 0;
}
int f(vector <int> &array)
{
n = array.size();
int i_0, i_1, i_2;
// these variables handle our base cases
i_1 = array[n-1];
i_2 = 0;
// this line handles the case where the input array
// has a single element
i_0 = i_1;
// iteratively update all three variables
// based on our recurrence relation.
for(i = n-2; i >= 0; i--)
{
i_0 = max(array[i] + i_2, i_1);
i_2 = i_1;
i_1 = i_0;
}
// the final answer is in i_0
return i_0;
}