BackmediumStackuncategorizedmedium

Optimal Speed Limit Adjustment Solution

Problem Statement

A traffic management system monitors a linear highway divided into n contiguous segments. For each segment i (0-indexed), the system records v_i, the current number of vehicles, and s_i, the average speed of those vehicles. The goal is to assign a new speed limit L_i to each segment such that the total congestion cost is minimized. The congestion cost for a segment is defined as the absolute difference between the assigned speed limit L_i and the product of the vehicle count and average speed (v_i * s_i), representing the deviation from the ideal flow capacity. You must determine the optimal speed limits for all segments to minimize the sum of these individual congestion costs. Note that speed limits must be non-negative integers.

Example 1
Input
vehicles = [2, 3], avgSpeeds = [10, 20]
Output
[20, 60]

Explanation: For segment 0: v_0 * s_0 = 2 * 10 = 20. The optimal limit is 20, cost |20 - 20| = 0. For segment 1: v_1 * s_1 = 3 * 20 = 60. The optimal limit is 60, cost |60 - 60| = 0. Total cost is 0. The output array contains the optimal limits [20, 60].

Example 2
Input
vehicles = [1, 1, 1], avgSpeeds = [5, 15, 25]
Output
[5, 15, 25]

Explanation: Segment 0: 1 * 5 = 5. Optimal limit 5. Segment 1: 1 * 15 = 15. Optimal limit 15. Segment 2: 1 * 25 = 25. Optimal limit 25. Since the product is already an integer, the optimal limit equals the product for each segment to achieve zero cost.

Example 3
Input
vehicles = [4, 2], avgSpeeds = [7, 3]
Output
[28, 6]

Explanation: Segment 0: 4 * 7 = 28. Optimal limit 28. Segment 1: 2 * 3 = 6. Optimal limit 6. The products are integers, so the optimal limits are exactly these values, resulting in a total congestion cost of 0.

Example 4
Input
vehicles = [10], avgSpeeds = [11]
Output
[110]

Explanation: Segment 0: 10 * 11 = 110. The optimal speed limit is 110 to minimize the absolute difference to zero.

Constraints

  • 1 <= n <= 10^5
  • 1 <= vehicles[i] <= 10^4
  • 1 <= avgSpeeds[i] <= 10^4
  • The product vehicles[i] * avgSpeeds[i] will not exceed 10^8
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

Optimal Speed Limit Adjustment — Problem Statement & Solution Guide

StackMediumMixed
TimeO(n)
|
SpaceO(n)

Problem Description

A traffic management system monitors a linear highway divided into n contiguous segments. For each segment i (0-indexed), the system records v_i, the current number of vehicles, and s_i, the average speed of those vehicles. The goal is to assign a new speed limit L_i to each segment such that the total congestion cost is minimized. The congestion cost for a segment is defined as the absolute difference between the assigned speed limit L_i and the product of the vehicle count and average speed (v_i * s_i), representing the deviation from the ideal flow capacity. You must determine the optimal speed limits for all segments to minimize the sum of these individual congestion costs. Note that speed limits must be non-negative integers.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Speed Limit Adjustment"

medium

WHY DOES IT MATTER?

Weighted L1 isotonic regression appears in many domains—traffic engineering, rating systems, and time‑series smoothing—where a monotone trend is required but raw measurements are noisy. Mastering PAVA equips engineers to enforce monotonicity with provably minimal distortion.

OPTIMIZATION CHALLENGE

The key insight is that the optimal value for a merged block is the weighted median of its original speeds, not the average. By storing cumulative weights and using a two‑pointer or binary‑search within each block, we can compute the median in O(1) amortized time, allowing the whole scan to run in O(n).

REAL-WORLD CONNECTION

Think of a distributed traffic‑control system that must broadcast speed limits to adjacent road sections. Abrupt changes cause driver confusion, so limits must form a smooth, non‑decreasing ramp. PAVA is analogous to a consensus protocol that merges conflicting proposals (blocks) until a globally consistent schedule emerges.

When coding PAVA, keep a stack of blocks (each with total weight, sum of speeds, and a data structure to retrieve the weighted median). Merging is just popping the top block, updating aggregates, and pushing the new merged block—this pattern avoids recursion and makes the solution interview‑ready.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
đź’ľ Space:O(n)

Core Theory — Why This Approach?

The problem is an instance of weighted L1 isotonic regression on a one‑dimensional chain. We must choose new speed limits L_i so that the sequence is non‑decreasing (or non‑increasing, depending on traffic policy) while minimizing the total weighted absolute deviation Σ v_i·|L_i‑s_i|. A naïve brute‑force that tries every possible monotone assignment is exponential because each segment can potentially merge with any of its neighbours, leading to O(2^n) possibilities. The optimal paradigm is the Pool Adjacent Violators Algorithm (PAVA). PAVA scans the array, maintains blocks of consecutive indices that currently satisfy the monotonicity constraint, and whenever a violation is detected it merges the offending blocks and replaces their values by the weighted median of the original s_i values inside the merged block. This merge‑and‑replace step guarantees that after each operation the partial solution is optimal for the processed prefix, and the algorithm finishes in linear time.

Interview Questions on This Problem

Q1How would you modify the solution if the monotonicity constraint were non‑increasing instead of non‑decreasing?

Reverse the direction of the inequality in the PAVA merge condition (i.e., merge when the current block’s representative value is greater than the next block’s). The rest of the algorithm – maintaining weighted medians for merged blocks – stays identical.

Q2Can the same approach be used if the cost function were squared error (L2) instead of absolute error (L1)?

Yes, but the block representative changes from a weighted median to a weighted mean. The PAVA still works for L2 isotonic regression, merging blocks whenever the mean of the left block exceeds the mean of the right block.

Q3Explain why a greedy “set L_i = s_i and then locally fix violations by adjusting the offending element” fails to produce the optimal total cost.

Local fixes ignore the impact on the weighted sum of absolute deviations of the whole block. Adjusting a single element may reduce its own cost but can increase the cost of many neighbours that later need to be merged, leading to a sub‑optimal global solution. PAVA’s block‑wise merging accounts for the collective effect, guaranteeing optimality.

Examples

Example 1

Input

vehicles = [2, 3], avgSpeeds = [10, 20]

Output

[20, 60]

Explanation: For segment 0: v_0 * s_0 = 2 * 10 = 20. The optimal limit is 20, cost |20 - 20| = 0. For segment 1: v_1 * s_1 = 3 * 20 = 60. The optimal limit is 60, cost |60 - 60| = 0. Total cost is 0. The output array contains the optimal limits [20, 60].

Example 2

Input

vehicles = [1, 1, 1], avgSpeeds = [5, 15, 25]

Output

[5, 15, 25]

Explanation: Segment 0: 1 * 5 = 5. Optimal limit 5. Segment 1: 1 * 15 = 15. Optimal limit 15. Segment 2: 1 * 25 = 25. Optimal limit 25. Since the product is already an integer, the optimal limit equals the product for each segment to achieve zero cost.

Example 3

Input

vehicles = [4, 2], avgSpeeds = [7, 3]

Output

[28, 6]

Explanation: Segment 0: 4 * 7 = 28. Optimal limit 28. Segment 1: 2 * 3 = 6. Optimal limit 6. The products are integers, so the optimal limits are exactly these values, resulting in a total congestion cost of 0.

Example 4

Input

vehicles = [10], avgSpeeds = [11]

Output

[110]

Explanation: Segment 0: 10 * 11 = 110. The optimal speed limit is 110 to minimize the absolute difference to zero.

Constraints

  • 1 <= n <= 10^5
  • 1 <= vehicles[i] <= 10^4
  • 1 <= avgSpeeds[i] <= 10^4
  • The product vehicles[i] * avgSpeeds[i] will not exceed 10^8

Optimal Approach & Strategy

Use the Pool Adjacent Violators Algorithm to merge violating adjacent blocks and assign each merged block the weighted median of its original speeds, achieving linear time.

Brute Force Approach

Enumerate every possible monotone assignment of speed limits and compute the total weighted absolute error; this is exponential in n.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function optimalSpeedLimits(vehicles, avgSpeeds) {
       // Initialize an empty array to store the optimal speed limits
       let optimalLimits = [];
       // Iterate over the average speeds
       for (let i = 0; i < avgSpeeds.length; i++) {
           // The optimal speed limit is the same as the average speed
           optimalLimits.push(avgSpeeds[i]);
       }
       // Return the optimal speed limits
       return optimalLimits;
   }

Asked in Top Tech Interviews

uncategorizedmediumgeneric

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.