Maximize watched duration under consecutive-sum limit
Company: TikTok
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Overview: This question evaluates algorithmic problem-solving in sequence optimization and constraint-based selection, testing competencies such as dynamic programming, subsequence selection, and handling pairwise adjacency constraints.
Read the full TikTok Data Scientist interview experience this question came from
Part 1: Maximize Watched Duration from an Ordered Subsequence
Constraints
- 0 <= len(d) <= 200000
- 1 <= d[i] <= 1000000000 for every valid i
- 0 <= A <= 1000000000
- The answer fits in a signed 64-bit integer.
Examples
Input: ([4, 2, 7, 3, 5], 7)
Expected Output: 11
Explanation: Choose durations [4, 2, 5]. Adjacent sums are 6 and 7, so the total is 11.
Input: ([], 10)
Expected Output: 0
Explanation: There are no videos, so watching nothing gives total 0.
Hints
- Let dp[i] be the best total watched duration for a valid subsequence that ends at video i.
- For video i with duration x, you need the maximum dp[j] among previous videos with d[j] <= A - x. Maintain prefix maximums over durations.
Part 2: Maximize Watched Duration with Replays and a Watch-Count Limit
Constraints
- 0 <= len(d) <= 5000
- 0 <= K <= 5000
- 1 <= d[i] <= 1000000000 for every valid i
- 0 <= A <= 1000000000
- Let m = len(set(d)). Test data satisfies m * max(1, K) <= 5000000.
Examples
Input: ([4, 2, 7, 3, 5], 7, 3)
Expected Output: 12
Explanation: Watch durations [5, 2, 5]. Both adjacent sums are 7, and the total is 12.
Input: ([1, 2, 3], 4, 0)
Expected Output: 0
Explanation: K is 0, so no videos may be watched.
Hints
- Because replays are allowed, the original indices no longer matter. The useful state is the last watched duration and how many videos have been watched.
- For each sequence length and next duration x, transition from the best previous state whose last duration is at most A - x. This can be accelerated with sorted durations and prefix maximums.