Sliding window · Medium
A cache analysis looks for the longest continuous period touching no more than k distinct resources. Repeated accesses to a resource do not consume additional distinct slots. The period cannot skip accesses in the middle.
Return the maximum length of a contiguous segment with at most k distinct input values.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], k: integer }
Fields
- nums is an array of signed integers. Repeated values at different positions are separate entries.
- k is the maximum number of distinct values allowed in the chosen segment.
Output
Return value
- Return a length, not indexes or the number of ranges. Empty input and k equal to zero return 0.
- Repeated values count once toward distinctness but every occurrence contributes to length.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
- 0 <= k <= 100000.
Examples
Example 1
{
"k": 2,
"nums": [
1,
2,
1,
3,
3
]
}Returns
3Example 2
{
"k": 1,
"nums": [
4,
4,
4
]
}Returns
3Required complexity
O(n) expected time and O(min(n, k + 1)) auxiliary space