Skip to content

Commit 6bdfc0c

Browse files
authored
Create greatest-sum-divisible-by-three.cpp
1 parent 35526c4 commit 6bdfc0c

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maxSumDivThree(vector<int>& nums) {
7+
vector<int> dp(3);
8+
for (const auto& num : nums) {
9+
vector<int> new_dp(dp);
10+
for (auto& x : dp) {
11+
x += num;
12+
}
13+
for (const auto& i : dp) {
14+
new_dp[i % 3] = max(new_dp[i % 3], i);
15+
}
16+
dp = move(new_dp);
17+
}
18+
return dp[0];
19+
}
20+
};

0 commit comments

Comments
 (0)