Find Maximum and Count Occurrences

Easy9 min
Given a non-empty integer array nums, return two values in this order: the largest value and the number of times it appears.

For nums = [-4, -1, -1, -3], initializing the maximum to 0 would return a value that never appeared in the array. Before the loop begins, the processed part contains only nums[0], so initialize maximum = nums[0] and count = 1.

After each iteration, maximum is the largest value seen so far, and count is the number of times that value appears in the processed part of the array. A larger value becomes the new maximum, and its count begins at 1. An equal value adds another occurrence. A smaller value cannot affect either result.

Why must count reset to 1 when a larger value is found?

Check equality only when the value was not larger than maximum. Otherwise, after a larger value becomes the new maximum and sets count = 1, an independent equality check would count that same element a second time. Python expresses this with elif, and the other languages use else if.

1def maximum_and_count(nums: list[int]) -> tuple[int, int]:
2 maximum = nums[0]
3 count = 1
4
5 for i in range(1, len(nums)):
6 value = nums[i]
7
8 if value > maximum:
9 maximum = value
10 count = 1
11 elif value == maximum:
12 count += 1
13
14 return maximum, count
Time: O(n)Space: O(1)

The first value initializes the state, and the loop examines each of the remaining n - 1 values once, giving O(n) time. The maximum and its count use O(1) auxiliary space. The returned pair has constant size.