1-bit and 2-bit Characters — linear scan
Keep a running answer while you walk the array once. Built for LeetCode 717. 1-bit and 2-bit Characters.
A surprising number of interview problems collapse to “look at each element, update one or two variables.” Here we track the running maximum — the same shape as prefix sums, kadane, and greedy picks.
Algorithm
- Seed
bestwith the first element. - For each later
x, setbest = max(best, x). - Return
best.
- Time
- O(n)
- Space
- O(1)
class Solution: def solve1BitAnd2BitCharacters(self, nums: list[int]) -> int: best = nums[0] for x in nums[1:]: if x > best: best = x return best