#3Longest Stable Battle Formation
The kingdom of Valoria is preparing its army for an important battle.
The soldiers are standing in a single continuous formation. Each soldier belongs to a particular unit, represented by an integer in the array units.
The commander wants to select a continuous group of soldiers from the formation. A battle formation is considered stable if no unit appears more than k times in the selected group.
Given an integer array units and an integer k, return the maximum number of consecutive soldiers that can be selected while keeping the formation stable.
A subarray is a contiguous, non-empty sequence of soldiers from the original formation.
Expected Complexity Time: O(n) Space: O(n)
Examples
Example 1
Input: units = [1,2,3,1,2,3,1,2], k = 2
Output: 6
Explanation: The longest stable battle formation is [1,2,3,1,2,3]. Unit 1 appears 2 times. Unit 2 appears 2 times. Unit 3 appears 2 times. No unit appears more than 2 times.
Example 2
Input: units = [1,2,1,2,1,2,1,2], k = 1
Output: 2
Explanation: Each unit can appear at most once. A valid formation is [1,2] or [2,1]. Therefore, the maximum length is 2.
Constraints
- 1 <= units.length <= 10^5
- 1 <= units[i] <= 10^9
- 1 <= k <= units.length
