-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#09.cpp
More file actions
33 lines (29 loc) · 683 Bytes
/
#09.cpp
File metadata and controls
33 lines (29 loc) · 683 Bytes
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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
// At each iteration, track the largest sum including and excluding the previous value
int largestNonAdjacentSum(vector<int> &v) {
int sumExcl = 0;
int sumIncl = v[0];
for (int i = 1; i < v.size(); i++) {
int temp = max(sumExcl, sumIncl);
sumIncl = sumExcl + v[i];
sumExcl = temp;
}
return max(sumExcl, sumIncl);
}
int main() {
string input;
while (getline(cin, input)) {
vector<int> v;
istringstream ss(input);
string token;
while (getline(ss, token, ',')) {
v.push_back(stoi(token));
}
cout << largestNonAdjacentSum(v) << endl;
}
}