Maximize Active Section with Trade I - Problem
You are given a binary string s of length n, where:
'1'represents an active section'0'represents an inactive section
You can perform at most one trade to maximize the number of active sections in s.
In a trade, you:
- Convert a contiguous block of
'1's that is surrounded by'0's to all'0's - Afterward, convert a contiguous block of
'0's that is surrounded by'1's to all'1's
Return the maximum number of active sections in s after making the optimal trade.
Note: Treat s as if it is augmented with a '1' at both ends, forming t = '1' + s + '1'. The augmented '1's do not contribute to the final count.
Input & Output
Example 1 — Basic Trade
$
Input:
s = "10110"
›
Output:
3
💡 Note:
Original has 3 ones. No beneficial trade exists: trading any 1-block for 0-block results in net loss or no gain.
Example 2 — Beneficial Trade
$
Input:
s = "1001"
›
Output:
3
💡 Note:
Original has 2 ones. Trade the middle 00 block for one of the 1 blocks: lose 1 one, gain 2 ones, net +1. Result: 2 + 1 = 3.
Example 3 — All Zeros
$
Input:
s = "0000"
›
Output:
0
💡 Note:
No 1-blocks to trade away, so no trade is possible. Result remains 0.
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string with 1s (active) and 0s (inactive)
2
Find Trades
Identify blocks of 1s and 0s for trading
3
Optimize
Choose trade that maximizes active sections
Key Takeaway
🎯 Key Insight: The optimal trade maximizes net gain (zeros gained minus ones lost)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code