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
โข
โข
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
2. Activate: Convert a contiguous block of
The string is treated as if it has virtual
Goal: Return the maximum number of active sections possible after making the optimal trade.
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 sectionYou 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's2. Activate: Convert a contiguous block of
'0's surrounded by '1's to all '1'sThe 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
โ Linear Growth
Space Complexity
O(k)
Where k is number of tradeable segments, typically much smaller than n
โ Linear Space
Constraints
- 1 โค n โค 105
- s consists only of characters '0' and '1'
- At most one trade can be performed
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code