Your question is Sliding Window Optimization. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
During a TikTok Shop live stream, product IDs are recorded in viewing order. Find the longest contiguous segment containing at most k distinct product IDs.
Use a sliding window that expands to include new products and shrinks from the left whenever the window contains more than k distinct IDs.
Implement longest_product_segment(product_ids, k).
product_ids, a list of integers representing product IDs, and k, a positive integer limit on distinct products.k distinct product IDs.def longest_product_segment(product_ids, k):