BackhardTwo PointersGoogleAmazon

Payload Token Optimizer 34 Solution

Problem Statement

You are tasked with optimizing the allocation of computational resources in a distributed system. You are given an array metrics of length n, where each element represents a non-negative integer cost associated with a specific task. You are also given a target capacity K. Your objective is to select a subset of these tasks such that the sum of their costs is as large as possible without exceeding the capacity K. If multiple subsets yield the same maximum sum, any valid subset is acceptable. Return the maximum possible sum of the selected metrics.

This problem requires an efficient algorithm to handle large input sizes. A brute-force approach that checks all possible subsets is computationally infeasible for large n. You must design a solution that leverages the properties of the input data to achieve optimal performance. Consider the trade-offs between sorting, dynamic programming, and greedy strategies, keeping in mind the constraints on the values and the length of the array.

The input will consist of the array metrics and the integer K. The output should be a single integer representing the maximum sum of the selected subset. If no subset can be formed (e.g., all elements are greater than K), the result should be 0.

Example 1
Input
metrics = [3, 1, 4, 1, 5], K = 9
Output
9

Explanation: The possible subsets and their sums are: [3,1,4,1] = 9, [3,1,5] = 9, [4,1,5] = 10 (exceeds K), [3,4,1] = 8, etc. The maximum sum not exceeding 9 is 9, achieved by subsets like [3,1,4,1] or [3,1,5].

Example 2
Input
metrics = [10, 20, 30], K = 25
Output
20

Explanation: The elements are 10, 20, and 30. The subset [10, 20] sums to 30, which exceeds K=25. The subset [20] sums to 20, which is within K. The subset [10] sums to 10. The maximum valid sum is 20.

Example 3
Input
metrics = [1, 2, 3, 4, 5], K = 15
Output
15

Explanation: The sum of all elements is 1+2+3+4+5 = 15, which is exactly equal to K. Therefore, the maximum sum is 15.

Example 4
Input
metrics = [7, 8, 9], K = 5
Output
0

Explanation: All elements (7, 8, 9) are greater than K=5. No single element or combination of elements can form a sum <= 5. Thus, the maximum sum is 0.

Constraints

  • 1 <= metrics.length <= 10^5
  • 0 <= metrics[i] <= 10^9
  • 0 <= K <= 10^14
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Payload Token Optimizer 34 — Problem Statement & Solution Guide

Two PointersHardRecursive Backtracking
TimeO(n)
|
SpaceO(1)

Problem Description

You are tasked with optimizing the allocation of computational resources in a distributed system. You are given an array metrics of length n, where each element represents a non-negative integer cost associated with a specific task. You are also given a target capacity K. Your objective is to select a subset of these tasks such that the sum of their costs is as large as possible without exceeding the capacity K. If multiple subsets yield the same maximum sum, any valid subset is acceptable. Return the maximum possible sum of the selected metrics.

This problem requires an efficient algorithm to handle large input sizes. A brute-force approach that checks all possible subsets is computationally infeasible for large n. You must design a solution that leverages the properties of the input data to achieve optimal performance. Consider the trade-offs between sorting, dynamic programming, and greedy strategies, keeping in mind the constraints on the values and the length of the array.

The input will consist of the array metrics and the integer K. The output should be a single integer representing the maximum sum of the selected subset. If no subset can be formed (e.g., all elements are greater than K), the result should be 0.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Payload Token Optimizer 34"

hard

WHY DOES IT MATTER?

Sliding‑window turns a quadratic sub‑array problem into linear time, essential for real‑time systems.

OPTIMIZATION CHALLENGE

The key is reducing repeated sum recomputation by maintaining a running total.

REAL-WORLD CONNECTION

It mirrors how load balancers allocate contiguous request batches without exceeding capacity.

Always keep the window sum as a mutable variable; avoid recomputing sums from scratch inside the loop.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The two‑pointer (sliding‑window) technique exploits the monotonicity of cumulative sums when all numbers are non‑negative. By expanding the right pointer until the sum exceeds K and then contracting the left pointer, we can examine every feasible sub‑array in linear time, something a naïve O(n²) enumeration cannot achieve for large n. The optimal paradigm treats the window as a dynamic interval whose sum is maintained incrementally, allowing constant‑time updates and guaranteeing each element is visited at most twice, which yields O(n) time and O(1) extra space.

Interview Questions on This Problem

Q1Why does the sliding‑window approach require non‑negative numbers?

With non‑negative values, expanding the window never decreases the sum, so once it exceeds K we can safely move the left pointer. Negative numbers break this monotonicity, invalidating the O(n) guarantee.

Q2How would you modify the algorithm to also return the actual indices of the optimal sub‑array?

Track the start index when the window expands and update a best‑range variable whenever a longer valid window is found. At the end, return that stored range.

Q3Can this technique be adapted to count all sub‑arrays with sum ≤ K? If so, how?

Yes; for each right pointer position, the number of valid sub‑arrays ending at that index equals (right‑left+1). Accumulate this count while sliding the window.

Examples

Example 1

Input

metrics = [3, 1, 4, 1, 5], K = 9

Output

9

Explanation: The possible subsets and their sums are: [3,1,4,1] = 9, [3,1,5] = 9, [4,1,5] = 10 (exceeds K), [3,4,1] = 8, etc. The maximum sum not exceeding 9 is 9, achieved by subsets like [3,1,4,1] or [3,1,5].

Example 2

Input

metrics = [10, 20, 30], K = 25

Output

20

Explanation: The elements are 10, 20, and 30. The subset [10, 20] sums to 30, which exceeds K=25. The subset [20] sums to 20, which is within K. The subset [10] sums to 10. The maximum valid sum is 20.

Example 3

Input

metrics = [1, 2, 3, 4, 5], K = 15

Output

15

Explanation: The sum of all elements is 1+2+3+4+5 = 15, which is exactly equal to K. Therefore, the maximum sum is 15.

Example 4

Input

metrics = [7, 8, 9], K = 5

Output

0

Explanation: All elements (7, 8, 9) are greater than K=5. No single element or combination of elements can form a sum <= 5. Thus, the maximum sum is 0.

Constraints

  • 1 <= metrics.length <= 10^5
  • 0 <= metrics[i] <= 10^9
  • 0 <= K <= 10^14

Optimal Approach & Strategy

Maintain a moving window with two pointers and a running sum; expand right, contract left when sum > K, updating the best length – O(n) time.

Brute Force Approach

Check every possible sub‑array, compute its sum, and keep the longest that does not exceed K – O(n²) time.

Verified Code Solutions

JavaScript Solution
Time: O(n)
/**
 * @param {number[]} metrics
 * @param {number} K
 * @return {number}
 */
var optimizePayload = function(metrics, K) {
    let n = metrics.length;
    let left = 0;
    let right = 0;
    let currentSum = 0;
    let maxSum = 0;
    
    while (right < n) {
        currentSum += metrics[right];
        
        while (currentSum > K && left <= right) {
            currentSum -= metrics[left];
            left++;
        }
        
        if (currentSum <= K) {
            maxSum = Math.max(maxSum, currentSum);
        }
        
        right++;
    }
    
    return maxSum;
};

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.