#3501

Maximize Active Section with Trade II

Hard
ArrayStringBinary SearchSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Identify segments of '1's and '0's, then calculate the maximum active sections by merging segments intelligently. This avoids redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Parse the string into segments of '1's and '0's, assigning IDs to each segment.
  2. 2Step 2: For each query, check the segments around the trade position and calculate the potential new active sections.
  3. 3Step 3: Return the maximum possible active sections after the optimal trade.
solution.py22 lines
1def maxActiveSections(s, queries):
2    segments = []
3    count = 0
4    for char in s:
5        if char == '1':
6            if count >= 0:
7                count += 1
8            else:
9                segments.append(count)
10                count = 1
11        else:
12            if count <= 0:
13                count -= 1
14            else:
15                segments.append(count)
16                count = -1
17    segments.append(count)
18    results = []
19    for l, r in queries:
20        max_count = segments[l - 1] + segments[r + 1] if l > 0 and r < len(segments) - 1 else 0
21        results.append(max_count)
22    return results

Complexity note: The complexity is linear since we only traverse the string and segments once, making it efficient.

  • 1Identify segments of '1's and '0's.
  • 2Merging segments intelligently maximizes active sections.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.