2288B1 — Yukari Yakumo and the Boundary Stones | Greedy Approach
Problem: Codeforces 2288B1
I solved this problem using a greedy approach instead of the usual DP approach. Here is the observation behind my solution.
Observation
We have two types of stones:
xstones of power 1ystones of power 2
Initially, the number of stones is x + y.
We need to maximize the number of stones after performing some prefix of the given string.
Let's maintain the number of stones of power 1 and power 2 separately.
Greedy Strategy
Case 1: The current character is +
If we already have at least one stone of power 2, we can simply copy it.
if(y) y++;
This increases the total number of stones by 1.
Otherwise, we must convert a power-1 stone into a power-2 stone.
else {
y++;
x--;
}
The total number of stones remains unchanged.
Case 2: The current character is -
This is the interesting part.
If we have at least two stones of power 2, we can decrease the power of one of them.
y--;
x++;
The total number of stones remains unchanged, and we still have a power-2 stone available for future + operations.
But what if y == 1 and x > 0?
In this case, we have only one power-2 stone.
If we decrease its power, we lose the ability to copy a power-2 stone in the next + operation.
So instead, I prefer to remove a power-1 stone and save the only power-2 stone.
if(y == 1 && x) {
x--;
}
This is the key greedy observation: when only one power-2 stone is left, preserve it whenever possible.
If there is no power-1 stone available, we simply decrease the power-2 stone.
Why do we update maxi with x + y + 1?
Consider this part:
x--;
maxi = max(maxi, x + y + 1);
After removing a power-1 stone, the current number of stones becomes x + y.
However, the expression x + y + 1 represents the number of stones before the removal.
We don't want to lose the maximum number of stones that we had already achieved.
The initial value of maxi is also x + y, so the empty prefix is considered.
Complexity
We process every character at most once.
- Time Complexity:
O(m)per test case - Space Complexity:
O(m)for the string
The greedy approach is simple and uses only two counters to maintain the current state.



