Skip to content

Commit 6caeca7

Browse files
authored
Update moving-stones-until-consecutive.cpp
1 parent bf9d02c commit 6caeca7

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

C++/moving-stones-until-consecutive.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,22 @@ class Solution {
1313
s[2] - s[0] - 2};
1414
}
1515
};
16+
17+
// Time: O(1)
18+
// Space: O(1)
19+
class Solution2 {
20+
public:
21+
vector<int> numMovesStones(int a, int b, int c) {
22+
vector<int> stones = {a, b, c};
23+
sort(stones.begin(), stones.end());
24+
int left = 0, min_moves = numeric_limits<int>::max();
25+
int max_moves = stones.back() - stones.front() - (stones.size() - 1);
26+
for (int right = 0; right < stones.size(); ++right) {
27+
while (stones[right] - stones[left] + 1 > stones.size()) { // find window size <= len(stones)
28+
++left;
29+
}
30+
min_moves = min(min_moves, static_cast<int>(stones.size()) - (right - left + 1));
31+
}
32+
return {min_moves, max_moves};
33+
}
34+
};

0 commit comments

Comments
 (0)