Count the Number of Substrings With Dominant Ones — linear scan
Keep a running answer while you walk the array once. Built for LeetCode 3234. Count the Number of Substrings With Dominant Ones.
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 countTheNumberOfSubstringsWithDominantOnes(self, nums: list[int]) -> int: best = nums[0] for x in nums[1:]: if x > best: best = x return best