LeetCode Entry

3499. Maximize Active Section with Trade I

21.07.2026 medium 2026 kotlin rust

Max ones after replacing surrounding zeros

3499. Maximize Active Section with Trade I medium substack youtube

https://dmitrysamoylenko.com/leetcode/

21.07.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1427

Problem TLDR

Max ones after replacing surrounding zeros

Intuition

Count max of surrounding zeros plus total ones.

Approach

  • only 4 variables necessary, but we can count ones in the same loop, that adds variables

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code

    fun maxActiveSectionsAfterTrade(s: String): Int {
        var pp = 0; var p = 0; var c = 0; var ch = '1'
        return s.count {it=='1'}+s.maxOf { x ->
            if (x == ch) c++  else { pp = p; p = c; c = 1; ch = x }
            if (x == '0' && p>0 && pp>0) pp+c else 0
        }
    }
    pub fn max_active_sections_after_trade(s: String) -> i32 {
        let (mut pp, mut p, mut c, mut k) = (0, 0, 0, 0);
        s.bytes().filter(|&b| b == 49).count() as i32 + s.bytes().map(|b| {
            if b == k { c += 1 } else { (pp, p, c, k) = (p, c, 1, b) }
            if b == 48 && pp > 0 { pp + c } else { 0 }
        }).max().unwrap_or(0)
    }

Comments