PracHub
QuestionsPremiumCoachesLearningGuidesInterview Prep

Quick 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.

  • easy
  • TikTok
  • Coding & Algorithms
  • Data Scientist

Maximize watched duration under consecutive-sum limit

Company: TikTok

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Technical Screen

You have a list of videos in a feed. Video *i* has duration `d[i]` (positive integer). A user has an “attention span” limit `A`. You want to select a **subset of videos to watch** (keeping the original order, i.e., choose a subsequence of indices `i1 < i2 < ... < ik`) to **maximize total watched time**: \[ \text{maximize } \sum_{t=1}^{k} d[i_t] \] subject to the constraint that **any two consecutively watched videos** do not exceed the attention span when added: \[ d[i_t] + d[i_{t+1}] \le A \quad \text{for all } t = 1..k-1 \] ### Task Write an algorithm/function that returns the **maximum total watched duration** achievable. ### Assumptions / clarifications - `n = len(d)` can be large enough that brute-forcing all subsets is too slow. - Watching 0 or 1 video is always allowed. ### Follow-up If the user is allowed to **watch the same video multiple times**, how would you modify the approach? - To avoid an unbounded/infinite answer, assume there is an additional limit `K` = maximum number of videos the user can watch total (including repeats). Return the maximum total watched duration under the same consecutive-sum constraint.

Quick Answer: 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.

Part 1: Maximize Watched Duration from an Ordered Subsequence

You are given a feed of videos in a fixed order. Video i has positive integer duration d[i]. You may choose any subsequence of videos to watch, preserving the original order. The total watched duration is the sum of the chosen durations. The constraint is that every pair of consecutively watched videos must have durations whose sum is at most A. Watching zero or one video is always allowed. Return the maximum total watched duration achievable.

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.

Input: ([6, 7, 8], 5)

Expected Output: 8

Explanation: No two videos can be watched consecutively because every pair sum exceeds 5. The best single video has duration 8.

Input: ([1, 2, 3, 4], 10)

Expected Output: 10

Explanation: All adjacent pairs in the original list are compatible, so all videos can be watched.

Input: ([10, 1, 1], 2)

Expected Output: 10

Explanation: A single video can always be watched, even if its duration exceeds A. The two 1-duration videos total only 2.

Solution

def solution(d, A):
    from bisect import bisect_left, bisect_right

    if not d:
        return 0

    values = sorted(set(d))
    m = len(values)
    bit = [0] * (m + 1)

    def update(idx, val):
        while idx <= m:
            if val > bit[idx]:
                bit[idx] = val
            idx += idx & -idx

    def query(idx):
        best = 0
        while idx > 0:
            if bit[idx] > best:
                best = bit[idx]
            idx -= idx & -idx
        return best

    ans = 0
    for x in d:
        limit = A - x
        pos = bisect_right(values, limit)
        best_before = query(pos)
        cur = best_before + x
        if cur > ans:
            ans = cur

        compressed_idx = bisect_left(values, x) + 1
        update(compressed_idx, cur)

    return ans

Time complexity: O(n log m), where n = len(d) and m is the number of distinct durations.. Space complexity: O(m), where m is the number of distinct durations..

Hints

  1. Let dp[i] be the best total watched duration for a valid subsequence that ends at video i.
  2. 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

You are given a list of videos, where video i has positive integer duration d[i]. You may now watch videos in any order, and the same video may be watched multiple times. You may watch at most K videos total, including repeated watches. The constraint is that every pair of consecutively watched videos must have durations whose sum is at most A. Watching zero videos is allowed. Return the maximum total watched duration achievable.

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.

Input: ([], 10, 5)

Expected Output: 0

Explanation: There are no available videos.

Input: ([6, 7, 8], 5, 4)

Expected Output: 8

Explanation: No two videos can be consecutive, so the best choice is to watch the single duration-8 video.

Input: ([10, 1, 9], 10, 5)

Expected Output: 29

Explanation: Watch [9, 1, 9, 1, 9]. Every adjacent sum is 10, and the total is 29.

Solution

def solution(d, A, K):
    from bisect import bisect_right

    if K <= 0 or not d:
        return 0

    values = sorted(set(d))
    m = len(values)

    # prev[i] is the best total for the current length ending with values[i].
    prev = list(values)  # Length 1 sequences.
    ans = max(prev)

    if K == 1:
        return ans

    NEG = -10**30

    def bit_update(bit, idx, val):
        while idx <= m:
            if val > bit[idx]:
                bit[idx] = val
            idx += idx & -idx

    def bit_query(bit, idx):
        best = NEG
        while idx > 0:
            if bit[idx] > best:
                best = bit[idx]
            idx -= idx & -idx
        return best

    for _ in range(2, K + 1):
        bit = [NEG] * (m + 1)
        for i, total in enumerate(prev, 1):
            if total != NEG:
                bit_update(bit, i, total)

        cur = [NEG] * m
        any_state = False

        for i, x in enumerate(values):
            pos = bisect_right(values, A - x)
            if pos == 0:
                continue

            best_before = bit_query(bit, pos)
            if best_before == NEG:
                continue

            total = best_before + x
            cur[i] = total
            if total > ans:
                ans = total
            any_state = True

        if not any_state:
            break

        prev = cur

    return ans

Time complexity: O(K * m log m), where m is the number of distinct durations.. Space complexity: O(m), where m is the number of distinct durations..

Hints

  1. 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.
  2. 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.
Last updated: Jun 22, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,000+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Parse a nested list from a string - TikTok (medium)
  • Implement stacks, streaming median, and upward path sum - TikTok (easy)
  • Implement stack variants and path-sum check - TikTok (medium)
  • Find the longest palindromic substring - TikTok (easy)
  • Maximize sum with no adjacent elements - TikTok (medium)