Maximize Active Section with Trade I โ LeetCode Daily Python Solution (Zero Bridge trick)
๐ Jump to your level: ๐ข Beginner: 0:24โ7:30 ๐ก Intermediate: 7:30โ12:26 ๐ด Advanced: 12:26โ18:32 ๐ Full written solution: https://timepasshub2539-hue.github.io/leetcode-python/maximize-active-section-with-trade-i.html ๐ป Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/maximize-active-section-with-trade-i Chapters: 0:00 The Problem: Maximize Active Section with Trade I 0:24 ๐ข Beginner: Deleting 1s to GET more 1s? 0:45 Why this pattern is worth learning 1:09 What the problem is really asking 1:39 Let's try one tiny example by hand 2:13 Two simple ideas we'll use 2:42 The Zero Bridge idea 3:14 The one simple formula 3:44 The code, part 1: build the groups 4:11 The code, part 2: find the best bridge 4:37 Your turn โ try to guess 4:58 Here's the answer 5:22 The slow way that gets stuck 5:53 How fast each way is 6:27 Tricky cases that could trip us up 6:54 Quick recap of the Zero Bridge 7:30 ๐ก Intermediate: You delete ones to WIN ones 7:46 Why this pattern pays off 8:06 What the problem actually asks 8:23 Walk the tiny example 8:43 Meet the tools 8:57 The Zero Bridge 9:19 One formula, that's the payoff 9:43 Solution, part 1: build the runs 10:01 Solution, part 2: find the best bridge 10:21 Pause and predict 10:35 The reveal 10:51 The obvious approach that flails 11:13 Cost of each approach 11:36 Edge cases that try to break us 11:56 Recap: the Zero Bridge sticks 12:26 ๐ด Advanced: You delete ones to WIN ones 12:47 Why this pattern pays off 13:07 What the problem actually asks 13:30 Walk the tiny example 13:55 Meet the tools 14:18 The Zero Bridge 14:43 One formula, that's the payoff 15:15 Solution, part 1: build the runs 15:39 Solution, part 2: find the best bridge 16:03 Pause and predict 16:22 The reveal 16:45 The obvious approach that flails 17:09 Cost of each approach 17:29 Edge cases that try to break us 18:02 Recap: the Zero Bridge sticks 18:32 Quick Quiz! 18:38 ... 18:41 Answer 18:49 Round 2! 18:56 ... 18:58 Answer Learn to solve LeetCode's 'Maximize Active Section with Trade I' in Python, from beginner to advanced. We break down the counterintuitive idea: why deleting 1s can get you MORE active 1s. Meet the Zero Bridge trick and the one simple formula that makes it O(n). Full walkthrough: build the groups/runs, find the best bridge, plus edge cases, complexity, and quizzes. Perfect for coding interview prep and daily LeetCode practice. #leetcode #python #codinginterview #dsa #programming Watch next: - This 'Correct' Trade I Solution Fails One Case: https://youtu.be/i9zQuvdLqoM - Why the O(n) Segment Trick Beats Brute Force โ Maximize Active Section with Trade I LeetCode Python Solution: https://youtu.be/9HkkrKJlh3A - ๐ก Intermediate: Two ones become seven with one swap #shorts: https://youtu.be/hr8PheH1u_I
SEO PACKAGE
1. SEO Title
Maximize Active Sections With Trade I in Python โ The Zero Bridge Trick (O(n) LeetCode Solution)
2. SEO Subtitle
Learn why deleting a run of 1s can leave you with more 1s, and how a single counting idea turns this problem into a clean linear-time solution.
3. Featured Quote
"You erase a wall of 1s so two pools of 0s can merge โ then flood the whole gap. The 1s come back, and every 0 comes along for free."
4. Meta Description
Solve LeetCode 'Maximize Active Section with Trade I' in Python using the Zero Bridge trick. Full O(n) walkthrough, code, dry run, and edge cases.
5. URL Slug
maximize-active-section-with-trade-i-python-zero-bridge
6. Keywords
Maximize Active Section with Trade I, LeetCode Python solution, Zero Bridge trick, run-length encoding, binary string problem, coding interview prep, O(n) algorithm, greedy algorithm, sentinel guard technique, two pointer runs, daily LeetCode, Python DSA, string manipulation, exchange argument, active sections, disk defragmentation problem, prefix counting, interview algorithms, group by runs, optimal substructure
7. Tags
python, leetcode, coding-interview, algorithms, data-structures, run-length-encoding, greedy, strings, two-pointers, software-engineering, dsa, interview-prep, linear-time, sentinel-technique
Maximize Active Sections With Trade I: The Zero Bridge Trick in Python
8. Introduction
Some problems look intimidating on the surface and turn out to hide one small counting idea. Maximize Active Section with Trade I is exactly that kind of problem. It sounds like a simulation puzzle full of moving parts, but the entire thing collapses into a single number once you see it the right way.
Here is the part that trips people up on first read: you are going to delete some 1s and end up with more 1s than you started with. That feels backwards. By the end of this article, that sentence will feel obvious.
This problem is a favorite in coding interviews at companies like Google and Meta because it tests something deeper than string manipulation. It checks whether you can:
- Spot when a "do the operation and re-check" simulation is a trap.
- Reduce a scary-sounding operation to a run-length representation.
- Justify why a greedy choice is optimal using an exchange argument.
- Handle boundary conditions cleanly with a sentinel trick.
The real-world flavor is disk defragmentation and memory compaction: any time a system tidies scattered blocks and packs them together, this same shape appears. Learn the idea once and a whole family of binary-string problems opens up.
9. Problem Overview
You are given a binary string made only of 1s and 0s. A 1 is an active section (think "on") and a 0 is inactive ("off").
You may perform at most one trade, and a trade has two ordered steps:
- Pick a solid run of 1s that has
0s on both sides, and flip that entire run to0s. - Pick a solid run of 0s that has
1s on both sides, and flip that entire run to1s.
Your goal: return the maximum number of 1s the string can contain after the trade.
One important modeling detail: we imagine a phantom 1 glued to each end of the string. This gives the runs at the very edges a neighbor on both sides, so we never fall off the end when checking "what's next to me." These phantom 1s are sentinels โ they help us reason, but they never count toward the score.
10. Example
Let's start tiny.
Input: 0100
Glue a 1 on each end โ 101001.
Look at the lone 1 in the middle. It has 0s on both sides, so we're allowed to erase it (step 1). Once it's gone, all the 0s between the two outer 1s merge into a single block. We flood that block with 1s (step 2). The original portion now reads:
1111
Output: 4
We deleted a 1 and finished with four active sections. That is the whole trick in miniature.
Here's a second example to lock it in.
Input: 1000100
- Starting 1s: there are 2.
- The interior run of 1s (the single
1in the middle) has000on its left and00on its right. - Bridge gain =
3 + 2 = 5. - Answer =
2 + 5 = 7.
Output: 7 โ the entire string lights up.
11. Intuition
Two small ideas do all the work.
Idea 1 โ Group the string into runs. Instead of reading 0 0 0 1 0 0 character by character, describe it as "a run of three 0s, then a run of one 1, then a run of two 0s." This is run-length encoding. Each chunk of identical digits is a "run."
Idea 2 โ Count your starting 1s. That's your score before any move.
Now the heart of it, which I call the Zero Bridge.
Picture a run of 1s with a run of 0s on its left and a run of 0s on its right:
... 000 1111 00 ...
z1 1s z2
When you erase that run of 1s, it's like knocking down a wall. The z1 zeros on the left and the z2 zeros on the right join into one big block of zeros. Then you flood that whole block with 1s.
So what did you actually gain?
- The 1s you deleted come right back as 1s โ net zero on them.
- Every 0 in
z1andz2also becomes a 1 โ pure bonus.
That leads straight to the formula:
$$\text{answer} = (\text{starting 1s}) + \max_{\text{interior 1-run}} (z_1 + z_2)$$
The length of the erased 1-run never appears in the math, because it cancels itself out (you destroy k ones and refill k ones in the merged gap). Your only job is to find the 1-run with the fattest pair of zero neighbors.
That "mystery number" the problem revolves around? It was z1 + z2 all along.
12. Brute Force Solution
Idea: Actually simulate every possible trade. For each eligible run of 1s, perform the two flips, rebuild the string, count the 1s, and keep the best result.
Algorithm:
- For every candidate run of 1s with 0s on both sides:
- Flip that run to 0s.
- Flip the now-merged run of 0s to 1s.
- Count the 1s in the rebuilt string.
- Return the maximum count seen.
Advantages:
- Directly mirrors the problem statement, so it's easy to trust.
- Fine for tiny inputs and useful as a mental sanity check.
Disadvantages:
- Each trade touches and rebuilds the entire string.
- With many candidate runs, you rebuild thousands of times.
- Painfully slow on large inputs (e.g. 100,000 characters).
Complexity:
- Time:
O(nยฒ)โ up toO(n)candidate runs, each costingO(n)to rebuild, with a heavy constant from string reallocation. - Space:
O(n)for each rebuilt copy.
Honest take: this one isn't even worth writing. The optimal version is barely more code and enormously faster.
13. Optimal Solution
The Zero Bridge reads the string just twice โ once to build the runs, once to scan them.
Step 1 โ Add sentinels. Prepend and append a 1:
s = "0100" โ t = "101001"
Step 2 โ Count starting 1s on the original string s (not on t, so the sentinels don't pollute the count).
Step 3 โ Build the runs of t with a two-pointer sweep. Each run is stored as (digit, length).
For t = "101001":
| Index | Digit | Length | Role |
|---|---|---|---|
| 0 | 1 | 1 | sentinel (skip) |
| 1 | 0 | 1 | left zeros |
| 2 | 1 | 1 | interior 1-run |
| 3 | 0 | 2 | right zeros |
| 4 | 1 | 1 | sentinel (skip) |
Step 4 โ Scan the interior runs (skip the first and last, which are sentinels). For every run of 1s, add the lengths of its left and right zero neighbors and track the maximum.
Here the only interior 1-run has neighbors of length 1 and 2, so the best bridge is 3.
Step 5 โ Combine: answer = starting_ones + best_bridge = 2 + 3 = 5.
Because run-length encoding alternates bits, a run of 1s is always flanked by runs of 0s (except at the sentinel edges), so the "zeros on both sides" check is essentially guaranteed for interior 1-runs โ but we keep it as a clear statement of intent.
14. Python Code
class Solution:
def maxActiveSectionsAfterTrade(self, s: str) -> int:
# Count active sections BEFORE adding sentinels.
ones = s.count("1")
# Glue a phantom 1 to each end so edge runs have neighbors.
t = "1" + s + "1"
n = len(t)
# Build run-length groups: each run is (digit, length).
runs = []
i = 0
while i < n:
j = i
while j < n and t[j] == t[i]:
j += 1
runs.append((t[i], j - i))
i = j
# Scan interior runs; a bridge needs zeros on both sides.
best = 0
for k in range(1, len(runs) - 1):
digit, _ = runs[k]
if digit == "1":
left_zeros = runs[k - 1][1]
right_zeros = runs[k + 1][1]
best = max(best, left_zeros + right_zeros)
return ones + best
15. Code Walkthrough
ones = s.count("1")โ the starting score, taken on the original string so sentinels never inflate it. This ordering is load-bearing.t = "1" + s + "1"โ the sentinel guards. Every real run now has a neighbor on both sides, so boundary checks can't index out of range or wrongly reject an edge run.- The
whileloop is the standard linear group-by:jraces ahead as long as the digit stays the same, snipping out exactly one run per outer iteration. Each run is saved as(digit, length). range(1, len(runs) - 1)deliberately skips the sentinel runs at both ends, so the neighbor lookupsruns[k-1]andruns[k+1]are always safe.- For each interior run of
1s, we sum its two zero neighbors and keep the largest total inbest. beststarts at0, which is exactly what makes the "no eligible run" case return the untouched count for free.return ones + bestโ the whole reduction in one line.
16. Dry Run
Let's trace s = "1000100".
ones = 2(two1s in the original).t = "1" + "1000100" + "1" = "110001001".- Build runs of
t:
| Run # | Digit | Length | Notes |
|---|---|---|---|
| 0 | 1 | 2 | sentinel + leading 1 (skip run 0) |
| 1 | 0 | 3 | left zeros |
| 2 | 1 | 1 | interior 1-run |
| 3 | 0 | 2 | right zeros |
| 4 | 1 | 2 | trailing 1 + sentinel (skip run 4) |
- Scan
k = 1 .. 3:k = 1: digit0โ skip.k = 2: digit1โ left zeros3, right zeros2, total5.best = 5.k = 3: digit0โ skip.
answer = ones + best = 2 + 5 = 7. โ
The entire string turns on, matching our hand calculation.
17. Complexity Analysis
- Time:
O(n). We scan the string once to build the runs and once to scan them. Both passes are linear, and there are at mostO(n)runs. - Space:
O(n)as written, because we store the list of runs (plus theO(n)sentinel-augmented stringt).
Why these are correct: run-length encoding produces at most one run per character, so building and scanning are each bounded by n. No nested rebuild ever happens, which is precisely what kills the O(nยฒ) brute force.
18. Alternative Solutions
Rolling-window, O(1) auxiliary space. You don't actually need to materialize the full runs list. Since only three consecutive runs matter at any moment โ (prev_zero_len, cur_one_len, next_zero_len) โ you can fuse run-building and scanning into a single pass that carries just those few numbers.
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute-force simulation | O(nยฒ) |
O(n) |
Rebuilds string per trade |
| Zero Bridge (runs list) | O(n) |
O(n) |
Clear, easy to reason about |
| Zero Bridge (rolling window) | O(n) |
O(1) |
Best if memory is constrained |
Reach for the rolling-window version when an interviewer asks, "Can you do better on space?" It's the honest answer, and it's the same idea with a tighter footprint.
19. Edge Cases
- No interior 1-run has zeros on both sides:
beststays0, so we return the original count โ correct. - All zeros (
"0000"): no 1s to fill anything with;ones = 0, no eligible run, returns0. - All ones (
"1111"): a single run, nothing to trade, returns the original count unchanged. - Empty string (
""): sentinels maket = "11", one run, no interior runs, safe. - A 1-run touching an original edge: this is exactly the case the sentinels rescue. Without them, the neighbor lookup would either fault or wrongly reject the run.
20. Common Mistakes
- Counting 1s on the augmented string
tinstead of the originals. The two sentinel 1s would silently inflate your answer by 2. - Forgetting the sentinels entirely. Edge runs then have only one neighbor, and boundary checks either crash or misjudge eligibility.
- Adding the erased 1-run's length into the total. It cancels out โ including it double-counts.
- Off-by-one in the scan range. Using
range(0, len(runs))instead ofrange(1, len(runs) - 1)walks into the sentinel runs and indexes out of bounds. - Simulating every trade on large inputs. It "works" but times out at scale โ the classic
O(nยฒ)trap. - Assuming a longer 1-run is better. Run length is irrelevant; only the zero neighbors matter.
21. Interview Questions
- If the string is already all 1s, what's the answer? Unchanged โ the total count of 1s. With no zeros between groups, there's nothing to merge, so you gain nothing.
- When you fill a zero group, how many groups of 1s merge? Exactly two โ the 1-runs immediately left and right of that zero group. Erasing the wall between them lets them touch.
- Why is greedy-on-max-neighbor-sum optimal? A single trade only ever merges two adjacent zero runs. So the global best is just the best local merge, and one pass finds it (exchange argument: you destroy
kones and refillk, net zero on them). - Can you reduce the space to O(1)? Yes โ carry a rolling window of three run lengths instead of building the full list.
- What changes with k trades, weighted runs, or a streaming variant? Each generalization changes whether "run-length plus one scan" still buys optimality โ a great "now what if" follow-up to be ready for.
22. Similar Problems
- Max Consecutive Ones III (LeetCode 1004) โ sliding window over a binary string with a flip budget; same "runs of 0s between 1s" instinct.
- Binary Subarrays With Sum (930) โ counting over binary arrays with a window/prefix idea.
- Minimum Swaps to Group All 1's Together (1151/2134) โ grouping active elements, another "compaction" flavor.
- Longest Repeating Character Replacement (424) โ best window under a limited number of changes, the generalized cousin of this trade.
They're related because each one rewards seeing the string as runs rather than individual characters, then optimizing a simple quantity over those runs.
23. Key Takeaways
- Model the string as runs, not characters.
- Your answer is
starting_ones + max(z1 + z2)over interior 1-runs. - The erased 1-run's length cancels โ never include it.
- Sentinels turn ugly boundary logic into a clean, uniform scan.
- Recognize the
O(nยฒ)simulation trap and reduce to a single linear pass.
24. Watch the Video
Seeing the Zero Bridge animated makes the "delete 1s to gain 1s" moment click instantly. Watch the full walkthrough โ with the group-building, the bridge scan, and the timed quizzes โ here: {LINK}. Pause on the challenge sections and try them before the reveal; that's where the intuition really sticks.
25. About the Series
This is part of the Daily Python LeetCode series, where we take one problem a day and go from beginner-friendly intuition to interview-ready mastery. Every solution is written in clean, production-quality Python, with the why explained before the how. A new problem drops tomorrow at the same time โ and it uses this exact run-length trick to crack a harder compression puzzle.
26. Call To Action
If the Zero Bridge clicked for you:
- Subscribe on YouTube so you never miss a daily problem.
- Subscribe to the Substack for the full written breakdowns.
- Comment with your answer to the quiz โ did you get 7?
- Share this with someone prepping for coding interviews.
Off-by-one bugs are sneaky. That subscribe button is easy to find โ it's right there.
SOCIAL MEDIA
LinkedIn Post
Here's a coding interview problem that looks backwards until it suddenly makes perfect sense.
Maximize Active Section with Trade I (LeetCode) gives you a binary string. You're allowed one trade: erase a run of 1s that has 0s on both sides, then fill a run of 0s that has 1s on both sides. Goal: end with as many 1s as possible.
The counterintuitive part? You delete 1s and finish with more 1s.
Here's why. When you erase a run of 1s sitting between two pools of 0s, those pools merge into one big block. You then flood the whole block with 1s. The deleted 1s come right back โ and every 0 on both sides becomes a 1 for free.
That turns the entire problem into one formula:
answer = (starting 1s) + max(left zeros + right zeros) around any interior 1-run
The length of the run you erase never even appears in the math, because it cancels itself out.
The engineering lesson matters more than the puzzle:
โ Model the string as runs, not characters. โ Recognize the O(nยฒ) "simulate every move" trap and reduce to a single O(n) pass. โ Use sentinel guards to make boundary logic disappear.
This same run-length instinct shows up in disk defragmentation and memory compaction โ and in a whole family of interview questions at companies like Google and Meta.
Full Python solution, dry run, and edge cases in the article.
#Python #LeetCode #CodingInterview #Algorithms #DataStructures #SoftwareEngineering
Twitter/X Thread
1/ You delete 1s from a binary string and end up with MORE 1s.
Sounds impossible. It's a real LeetCode problem โ "Maximize Active Section with Trade I."
Here's the one trick that solves it in O(n). ๐งต
2/ The setup: a string of 1s (active) and 0s (inactive).
One trade, two steps: โข Erase a run of 1s that has 0s on both sides. โข Fill a run of 0s that has 1s on both sides.
Goal: maximize the 1s.
3/ Tiny example: 0100.
Glue a 1 on each end โ 101001.
The middle 1 has 0s on both sides. Erase it. Now all the 0s merge into one block. Fill it โ 1111.
Four 1s. From a string with one 1. ๐คฏ
4/ Two ideas do all the work: โข Group the string into RUNS (three 0s, then two 1s, โฆ). โข Count your starting 1s.
That's it. That's the whole toolkit.
5/ The key insight โ the Zero Bridge:
A run of 1s sits between two runs of 0s. Erase the 1s โ the 0s on both sides merge โ flood them with 1s.
The 1s you deleted come back. Every 0 becomes a 1 for FREE.
6/ So the formula is:
answer = (starting 1s) + max(left 0s + right 0s) around any interior 1-run
The erased run's length cancels out. It never appears. You're just hunting the fattest pair of zero neighbors.
7/ Try it: 1000100.
Starting 1s = 2. Middle 1-run has 000 left, 00 right โ bridge = 5.
Answer = 2 + 5 = 7. The whole string lights up.
8/ The trap: simulating every trade, rebuilding the string each time.
That's O(nยฒ) with a fat constant. On 100k characters it crawls.
The run version reads the string twice. O(n). Barely more code.
9/ Pro touches for interviews: โข Sentinel 1s on both ends kill all boundary bugs. โข You can drop to O(1) space with a rolling window of 3 run lengths. โข Optimality follows from an exchange argument.
10/ Recap: Group into runs โ count 1s โ find the fattest zero pair around a single 1-run โ add them.
That's the entire problem.
Full Python + dry run + edge cases in the article. Follow for a new LeetCode breakdown every day. ๐
Facebook Post
Ever heard of a puzzle where you delete things to end up with more of them? ๐
That's this LeetCode problem โ "Maximize Active Section with Trade I." You've got a string of 1s and 0s, you erase a block of 1s, and somehow you finish with more 1s than you started with.
The secret is something I call the Zero Bridge: when you erase a run of 1s between two pools of 0s, those pools merge into one โ and you fill the whole thing with 1s. The 1s come back, and every 0 tags along for free.
Once you see it, the whole problem becomes one simple formula, and the code runs in linear time. I break it all down step by step โ with examples, a dry run, and the sneaky edge cases โ in the full article and video. Give it a shot before the reveal! ๐
Reddit Summary
Maximize Active Section with Trade I โ the "delete 1s to gain 1s" problem, explained
This one confuses people on first read, so here's the intuition that makes it click.
You have a binary string. One trade: flip a run of 1s (with 0s on both sides) to 0s, then flip a run of 0s (with 1s on both sides) to 1s. Maximize the 1s.
The trick: when you erase a run of 1s sitting between two runs of 0s, those two zero runs merge into one block, and you flood it with 1s. The deleted 1s come back, and every 0 on both sides becomes a 1. So the run length you erase is irrelevant โ it cancels out.
That reduces the whole thing to:
answer = count_of_ones + max(left_zeros + right_zeros) over interior 1-runs.
Implementation notes that helped me:
- Run-length encode the string; only three consecutive runs ever matter.
- Add sentinel 1s to both ends so boundary runs have neighbors โ kills all off-by-one/index errors.
- The naive "simulate each trade and rebuild" is O(nยฒ); the run scan is O(n), and you can get O(1) extra space with a rolling window.
Optimality is an exchange argument: a single trade only merges two adjacent zero runs, so the global best is the best local merge. One pass finds it.
Curious how others handle the k-trades generalization โ does the single-scan reduction still hold, or do you need a different structure?
GITHUB README
# Maximize Active Section with Trade I
Python solution to LeetCode's **Maximize Active Section with Trade I**, solved in
**O(n)** time with the *Zero Bridge* trick.
## Problem
You're given a binary string where `1` is an active section and `0` is inactive.
You may perform **at most one trade**:
1. Pick a run of `1`s that has `0`s on both sides and flip it all to `0`s.
2. Pick a run of `0`s that has `1`s on both sides and flip it all to `1`s.
Return the **maximum number of active sections (`1`s)** you can end up with.
A phantom `1` is treated as glued to each end of the string, so edge runs have
neighbors on both sides.
## Intuition
The counterintuitive part: deleting a run of `1`s can leave you with *more* `1`s.
When a run of `1`s sits between two runs of `0`s, erasing it merges those two
zero runs into one block โ which you then flood with `1`s. The deleted `1`s come
right back, and **every `0` on both sides also becomes a `1`, for free**. That's
the *Zero Bridge*.
## Approach
1. Count the starting `1`s (on the original string).
2. Add sentinel `1`s to both ends.
3. Run-length encode into `(digit, length)` groups.
4. For each interior run of `1`s, sum its left and right zero neighbors and keep
the maximum (`best`).
5. Answer = `starting_ones + best`.
The erased run's length **cancels out** (destroy `k` ones, refill `k`), so it
never appears in the formula:
answer = count(1s) + max over interior 1-runs of (left_zeros + right_zeros)
## Python Solution
```python
class Solution:
def maxActiveSectionsAfterTrade(self, s: str) -> int:
ones = s.count("1") # count BEFORE adding sentinels
t = "1" + s + "1" # sentinel guards on both ends
n = len(t)
# Run-length encode into (digit, length) groups.
runs = []
i = 0
while i < n:
j = i
while j < n and t[j] == t[i]:
j += 1
runs.append((t[i], j - i))
i = j
# Scan interior runs; a bridge needs zeros on both sides.
best = 0
for k in range(1, len(runs) - 1):
if runs[k][0] == "1":
best = max(best, runs[k - 1][1] + runs[k + 1][1])
return ones + best
Complexity
| Metric | Value | Why |
|---|---|---|
| Time | O(n) |
One pass to build runs, one to scan them |
| Space | O(n) |
Stores the runs list; drops to O(1) with a rolling window |
Edge Cases
- No eligible interior 1-run โ
best = 0, returns the original count. - All
0s โ returns0. - All
1s โ returns the original count (nothing to trade). - Empty string โ sentinels make
t = "11", safe. - 1-run touching an original edge โ rescued by the sentinels.
Video
๐บ Full walkthrough: {LINK}
Article
Full write-up with intuition, dry run, alternative O(1)-space solution, common mistakes, and interview follow-ups โ part of the Daily Python LeetCode series. ```
The solution
best = 0
for i in range(1, len(runs) - 1):
bit, _ = runs[i]
if bit == '1' and runs[i-1][0] == '0' \
and runs[i+1][0] == '0':
best = max(best, runs[i-1][1] + runs[i+1][1])
return ones + bestReady to try it yourself? Solve Greedy problems with instant feedback in the practice sandbox.
Practice now โ


