Skip to content

Commit e5ff62d

Browse files
authored
Create last-stone-weight-ii.cpp
1 parent 7c257cc commit e5ff62d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

C++/last-stone-weight-ii.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n * s), s is sum(stones)
2+
// Space: O(s)
3+
4+
class Solution {
5+
public:
6+
int lastStoneWeightII(vector<int>& stones) {
7+
unordered_set<int> dp = {0};
8+
const auto& S = accumulate(stones.cbegin(), stones.cend(), 0);
9+
for (const auto& stone : stones) {
10+
auto tmp(dp);
11+
for (const auto& i : dp) {
12+
tmp.emplace(i + stone);
13+
}
14+
dp = move(tmp);
15+
};
16+
auto result = numeric_limits<int>::max();
17+
for (const auto& i : dp) {
18+
result = min(result, abs(i - (S - i)));
19+
}
20+
return result;
21+
}
22+
};

0 commit comments

Comments
 (0)