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 I INPUT Binary String s = "10110" 1 i=0 0 i=1 1 i=2 1 i=3 0 i=4 1 = Active 0 = Inactive Augmented: t = "1" + s + "1" 1 1 0 1 1 0 1 Gray = augmented (not counted) Initial Active: 3 ones ALGORITHM STEPS 1 Identify Blocks Find all 0-blocks and 1-blocks 2 Find Trade Options 0-block between 1-blocks 3 Calculate Gain Merge adjacent 1-blocks 4 Select Best Trade Maximize final count Trade Analysis: 0-block at i=1: size=1 0-block at i=4: size=1 Best: Fill 0 at i=1 Gain: merge "1"+"11" = "111" FINAL RESULT After Optimal Trade: 1 1 1 0 "1110" (conceptual result) Output: 3 Maximum Active Sections Verification: Original 1s: 3 Trade: None needed Result: 3 [OK] Key Insight: A trade converts a 1-block to 0s, then a 0-block to 1s. The optimal strategy is to fill a 0-block that merges two adjacent 1-blocks, maximizing total active sections. Enumerate all 0-blocks between 1-blocks and calculate the potential gain for each trade option. TutorialsPoint - Maximize Active Section with Trade I | Optimized Enumeration
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