[LeetCode] Maximize Active Section with Trade I

3499. Maximize Active Section with Trade I

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:

  • Convert a contiguous block of '1's that is surrounded by '0's to all '0's.
  • 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

func maxActiveSectionsAfterTrade(s string) int {
var cnt []int
one := 0

for i := 0; i < len(s); i++ {
if s[i] == '1' {
one++
} else {
if i == 0 || s[i-1] == '1' {
cnt = append(cnt, 1)
} else {
cnt[len(cnt)-1]++
}
}
}

if len(cnt) <= 1 {
return one
}

best := 0
for i := 0; i < len(cnt)-1; i++ {
best = max(best, cnt[i]+cnt[i+1])
}

return best + one
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/30/PS/LeetCode/maximize-active-section-with-trade-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.