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:

  1. Convert a contiguous block of '1's that is surrounded by '0's to all '0's
  2. 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
Maximize Active Section with Trade IInput String:10110Trade Process:1. Convert a 1-block to 0s (surrounded by 0s)2. Convert a 0-block to 1s (surrounded by 1s)3. Calculate net gain: zeros_gained - ones_lostPossible Trades:Trade [1,1] block → [0] block: Net gain = 1 - 2 = -1Trade [1] block → [0] block: Net gain = 1 - 1 = 0Optimal Result: 3 active sections (no beneficial trade)
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)
Asked in
Google 15 Microsoft 12
3.4K Views
Medium Frequency
~25 min Avg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen