Maximize watch time under adjacency constraint
Company: Bytedance
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This Coding & Algorithms question for a Data Engineer role evaluates dynamic programming and sequence-optimization skills by requiring selection of a subsequence under a pairwise adjacency constraint on video durations, at a moderate-to-advanced algorithmic abstraction level.
Part 1: Maximize Subsequence Watch Time Under Adjacent Duration Limit
Constraints
- 0 <= len(duration) <= 200000
- 0 <= duration[i] <= 10^9
- 0 <= A <= 10^9
- The answer fits in a signed 64-bit integer.
Examples
Input: ([], 10)
Expected Output: 0
Explanation: There are no videos, so the best total watch time is 0.
Input: ([12], 5)
Expected Output: 12
Explanation: A single video has no adjacent selected pair, so it can be watched even though its duration exceeds A.
Input: ([4, 2, 6, 3, 5], 8)
Expected Output: 14
Explanation: One optimal subsequence is [4, 2, 3, 5]. Adjacent sums are 6, 5, and 8, and the total is 14.
Input: ([8, 1, 7, 2, 6], 8)
Expected Output: 9
Explanation: One optimal subsequence is [1, 2, 6], with adjacent sums 3 and 8, for total 9.
Input: ([1, 2, 3, 2], 5)
Expected Output: 8
Explanation: All videos can be selected because adjacent sums are 3, 5, and 5.
Hints
- Let dp[i] be the maximum total watch time of a valid subsequence that must end at video i.
- For video i, you need the best dp[j] among earlier videos j where duration[j] <= A - duration[i]. Maintain these best values by duration and query a prefix maximum.
Part 2: Maximize Exact-Length Watch Session With Rewatching
Constraints
- 0 <= len(duration) <= 2000
- 0 <= m <= 2000
- 0 <= duration[i] <= 10^9
- 0 <= A <= 10^9
- The answer fits in a signed 64-bit integer.
Examples
Input: ([], 10, 0)
Expected Output: 0
Explanation: Exactly zero selections means the empty session, which is valid.
Input: ([12, 3], 5, 1)
Expected Output: 12
Explanation: With only one selection, there is no adjacency constraint, so choose the longest video.
Input: ([4, 2, 6, 3, 5], 8, 4)
Expected Output: 16
Explanation: One optimal session is [6, 2, 6, 2], where every adjacent sum is 8.
Input: ([8, 1, 7, 2, 6], 8, 5)
Expected Output: 23
Explanation: One optimal session is [7, 1, 7, 1, 7], with total 23.
Input: ([6, 7], 5, 2)
Expected Output: -1
Explanation: No pair of selections can satisfy the adjacent-sum limit, so a session of length 2 is impossible.
Hints
- Use dynamic programming over the session length: dp[t][d] can represent the best total for a length-t session ending with duration d.
- For each next duration d, the previous duration must be at most A - d. Sorting distinct durations lets you use prefix maximums to speed up each transition round.