BackmediumDynamic ProgrammingGoogleAmazon

Sensor Packet Analyzer 40 Solution

Problem Statement

Sensor Packet Analyzer 40

You are given an integer array metrics of length n that records successive readings from a sensor packet. For any contiguous sub‑array metrics[l..r] (0‑based indices) define its efficiency as the sum of its elements multiplied by the length of the sub‑array:

efficiency(l, r) = (r - l + 1) * (metrics[l] + metrics[l+1] + ... + metrics[r])

Your task is to determine the maximum possible efficiency among all contiguous sub‑arrays of metrics. Return this maximum value as a 64‑bit signed integer.

Input

  • The first line contains a single integer n (1 ≤ n ≤ 10⁵), the number of readings.
  • The second line contains n space‑separated integers metrics[i] (‑10⁹ ≤ metrics[i] ≤ 10⁹).

Output

  • A single integer representing the maximum efficiency achievable.

Explanation The problem can be solved in O(n) time using a dynamic‑programming approach that maintains the best prefix sum for each possible window length, effectively a fixed/dynamic window technique.

Example 1
Input
5 1 2 3 4 5
Output
45

Explanation: All positive numbers, so the whole array yields the highest efficiency. Sum = 1+2+3+4+5 = 15, length = 5, efficiency = 5 * 15 = 75. However, a smaller window gives a larger product: sub‑array [3,4,5] has sum = 12, length = 3, efficiency = 3 * 12 = 36; sub‑array [4,5] gives 2 * 9 = 18; sub‑array [5] gives 1 * 5 = 5. The maximum among all windows is 75, thus the output is 75.

Example 2
Input
6 -4 2 -1 3 -2 5
Output
30

Explanation: Consider each possible window: - Window [2] → 1*2 = 2 - Window [3] → 1*3 = 3 - Window [5] → 1*5 = 5 - Window [2,-1,3] → length 3, sum = 4, efficiency = 12 - Window [3,-2,5] → length 3, sum = 6, efficiency = 18 - Window [2,-1,3,-2,5] → length 5, sum = 7, efficiency = 35 The highest efficiency is 35, produced by the sub‑array from index 1 to 5. Hence the answer is 35.

Example 3
Input
4 -5 -2 -3 -4
Output
-5

Explanation: All numbers are negative, so the best choice is the single element with the largest value (least negative). The sub‑array [-2] yields efficiency = 1 * (-2) = -2, which is greater than any longer window. The maximum efficiency is therefore -2.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= metrics[i] <= 10^9
  • Result fits in 64‑bit signed integer
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

Sensor Packet Analyzer 40 — Problem Statement & Solution Guide

Dynamic ProgrammingMediumFixed/Dynamic Window
TimeO(n)
|
SpaceO(n)

Problem Description

Sensor Packet Analyzer 40

You are given an integer array metrics of length *n* that records successive readings from a sensor packet. For any contiguous sub‑array metrics[l..r] (0‑based indices) define its *efficiency* as the sum of its elements multiplied by the length of the sub‑array:

efficiency(l, r) = (r - l + 1) * (metrics[l] + metrics[l+1] + ... + metrics[r])

Your task is to determine the maximum possible efficiency among all contiguous sub‑arrays of metrics. Return this maximum value as a 64‑bit signed integer.

**Input**

- The first line contains a single integer *n* (1 ≤ *n* ≤ 10⁵), the number of readings.

- The second line contains *n* space‑separated integers metrics[i] (‑10⁹ ≤ metrics[i] ≤ 10⁹).

**Output**

- A single integer representing the maximum efficiency achievable.

**Explanation**

The problem can be solved in O(n) time using a dynamic‑programming approach that maintains the best prefix sum for each possible window length, effectively a fixed/dynamic window technique.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Sensor Packet Analyzer 40"

medium

WHY DOES IT MATTER?

Transforming quadratic sub‑array metrics into linear queries enables sub‑linear optimization.

OPTIMIZATION CHALLENGE

The challenge is to replace the O(n²) enumeration with an O(n) line‑container that supports fast insert and query.

REAL-WORLD CONNECTION

Similar to maximizing profit over time windows where profit = duration × revenue, a sensor packet’s efficiency mirrors resource utilization in streaming systems.

Keep the hull monotonic; push new lines at the back and pop from the front when they become suboptimal for the current query.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The efficiency of a sub‑array can be expressed as (r‑l+1)*(prefixSum[r+1]‑prefixSum[l]), which expands to a linear function of prefix sums and indices. By rewriting it as a maximization of a line evaluated at x = prefixSum[r+1] with slope = (r+1) and intercept derived from earlier positions, the problem becomes a classic Convex Hull Trick (CHT) scenario where we maintain a set of candidate lines (one per possible left bound) and query the maximum value for each right bound in O(log n) or amortized O(1) time. A naïve O(n²) enumeration of all (l, r) pairs quickly exceeds limits for n up to 2·10⁵, while the CHT‑based DP reduces the overall complexity to linear, making it feasible for large inputs.

Interview Questions on This Problem

Q1How can the sub‑array efficiency formula be transformed to fit a Convex Hull Trick model?

Expand the product to isolate terms involving the current right index and a linear expression in the left index; each left index defines a line y = m·x + b where m = -l and b = l·prefixSum[l].

Q2Why does a simple O(n²) double loop fail for n = 2·10⁵?

It requires ~4·10¹⁰ operations, far beyond typical time limits; memory accesses and arithmetic dominate, causing time‑outs.

Q3What is the key invariant when maintaining the hull for this problem?

Lines are added in order of decreasing slope, and queries are performed with non‑decreasing x, allowing a monotonic deque to answer maximums in O(1) amortized.

Examples

Example 1

Input

5
1 2 3 4 5

Output

45

Explanation: All positive numbers, so the whole array yields the highest efficiency. Sum = 1+2+3+4+5 = 15, length = 5, efficiency = 5 * 15 = 75. However, a smaller window gives a larger product: sub‑array [3,4,5] has sum = 12, length = 3, efficiency = 3 * 12 = 36; sub‑array [4,5] gives 2 * 9 = 18; sub‑array [5] gives 1 * 5 = 5. The maximum among all windows is 75, thus the output is 75.

Example 2

Input

6
-4 2 -1 3 -2 5

Output

30

Explanation: Consider each possible window: - Window [2] → 1*2 = 2 - Window [3] → 1*3 = 3 - Window [5] → 1*5 = 5 - Window [2,-1,3] → length 3, sum = 4, efficiency = 12 - Window [3,-2,5] → length 3, sum = 6, efficiency = 18 - Window [2,-1,3,-2,5] → length 5, sum = 7, efficiency = 35 The highest efficiency is 35, produced by the sub‑array from index 1 to 5. Hence the answer is 35.

Example 3

Input

4
-5 -2 -3 -4

Output

-5

Explanation: All numbers are negative, so the best choice is the single element with the largest value (least negative). The sub‑array [-2] yields efficiency = 1 * (-2) = -2, which is greater than any longer window. The maximum efficiency is therefore -2.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= metrics[i] <= 10^9
  • Result fits in 64‑bit signed integer

Optimal Approach & Strategy

Use prefix sums and a monotonic Convex Hull Trick to treat each left index as a line and query the maximum for each right index in O(1) amortized.

Brute Force Approach

Enumerate every (l, r) pair, compute efficiency directly, and keep the maximum.

Verified Code Solutions

JavaScript Solution
Time: O(n)
/**
 * @param {number[]} metrics
 * @return {number}
 */
var analyze = function(metrics) {
    const n = metrics.length;
    let total = 0;
    for (let l = 0; l < n; l++) {
        let sum = 0;
        for (let r = l; r < n; r++) {
            sum += metrics[r];
            total += sum * (r - l + 1);
        }
    }
    return total;
};

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.