Maximize Active Section with Trade I - Problem
Maximize Active Section with Trade I

You are managing a system with active and inactive sections represented by a binary string s of length n:

โ€ข '1' represents an active section
โ€ข '0' represents an inactive section

You can perform at most one trade to maximize the number of active sections. A trade consists of two operations:

1. Deactivate: Convert a contiguous block of '1's surrounded by '0's to all '0's
2. Activate: Convert a contiguous block of '0's surrounded by '1's to all '1's

The string is treated as if it has virtual '1's at both ends: t = '1' + s + '1'. These virtual sections don't count toward the final result.

Goal: Return the maximum number of active sections possible after making the optimal trade.

Input & Output

example_1.py โ€” Basic Trade
$ Input: s = "01100"
โ€บ Output: 3
๐Ÿ’ก Note: Original string has 2 ones. We can deactivate the "11" (surrounded by 0s) and activate the "00" (surrounded by 1s after augmentation). Net gain = 2 - 2 = 0. No beneficial trade exists, so return original count of 2... Wait, let me recalculate. Original: "01100" has 2 ones. After augmentation: "1011001". The "11" at positions 2-3 can be deactivated, and "00" at positions 4-5 can be activated. But this gives no net gain. Actually, return 2.
example_2.py โ€” Beneficial Trade
$ Input: s = "0110"
โ€บ Output: 3
๐Ÿ’ก Note: Original: "0110" has 2 ones. Augmented: "101101". The "11" at positions 2-3 is surrounded by 0s, so can be deactivated (lose 2). The "0" at position 1 is surrounded by 1s, so can be activated (gain 1). Net = 1-2 = -1, not beneficial. The "0" at position 4 is surrounded by 1s, so can be activated (gain 1). Net = 1-2 = -1. No beneficial single trade. Wait... let me reconsider the segments.
example_3.py โ€” No Trade Possible
$ Input: s = "1111"
โ€บ Output: 4
๐Ÿ’ก Note: All sections are already active. Augmented: "111111". No segments are surrounded by different characters, so no trades are possible. Return original count of 4.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through string with constant time operations per character

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

Where k is number of tradeable segments, typically much smaller than n

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 105
  • s consists only of characters '0' and '1'
  • At most one trade can be performed
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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