Shifted Path Weight — Problem Statement & Solution Guide
Problem Description
You are given an array of integers representing the weights of nodes in a linear path. The goal is to determine the maximum 'shifted path weight' achievable by selecting a contiguous subarray. The shifted path weight is defined as the product of the length of the subarray and the minimum value within that subarray. This metric models the maximum volume of a container formed by the height constraints of the path segments.
Your task is to compute the maximum value of (length * minimum_value) for any contiguous subarray of the input array. If the array contains negative numbers, the minimum value will be the most negative number, potentially resulting in a negative product. However, the problem assumes we are looking for the maximum possible value, which could be negative if all subarrays yield negative products.
Input: An array of integers nums.
Output: A single integer representing the maximum shifted path weight.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Shifted Path Weight"
WHY DOES IT MATTER?
The monotonic stack pattern is essential because it transforms a quadratic brute force into a linear scan, enabling solutions for large datasets. It is widely applicable to problems involving nearest smaller/greater elements, such as stock span, next greater element, and histogram area calculations.
OPTIMIZATION CHALLENGE
The core insight is that each element is the minimum for a unique maximal interval; by finding the nearest smaller elements on both sides, we avoid recomputing minima for overlapping subarrays, reducing the complexity from O(n^2) to O(n).
REAL-WORLD CONNECTION
Think of a warehouse with shelves of varying heights; the algorithm finds the widest stretch of shelves that can hold a crate of a given height. In distributed systems, it’s analogous to determining the largest contiguous block of servers that can handle a workload before a bottleneck occurs.
When explaining to interviewers, emphasize that the stack stores indices of increasing weights, and popping gives you the width of the subarray where the popped element is the smallest. Mention that the width is rightIndex - leftIndex - 1, and the area is weight * width.
COMPLEXITY AT A GLANCE
O(n)O(n)Core Theory — Why This Approach?
The problem is a classic instance of the "largest rectangle in a histogram" pattern. A naive approach would examine every possible contiguous subarray, compute its minimum weight, multiply by its length, and keep the maximum. This requires O(n^2) time and O(1) space, which quickly becomes infeasible for arrays with millions of elements. The optimal solution observes that for any position i, the element at i is the minimum of all subarrays that extend left until a smaller element appears and right until a smaller element appears. By precomputing, for each index, the nearest smaller element to its left and to its right, we can determine the maximum length of a subarray where a[i] is the minimum in O(1) time per index. A monotonic increasing stack yields these boundaries in a single left‑to‑right and right‑to‑left pass, giving an overall O(n) time and O(n) auxiliary space solution.
The key insight is that each element contributes to the answer only once: as the minimum of the widest subarray that still keeps it as the smallest value. By iterating over the array and using a stack to maintain indices of increasing weights, we can pop indices when we encounter a smaller weight, compute the area for the popped index, and push the current index. This technique guarantees linear time because each index is pushed and popped at most once.
Interview Questions on This Problem
Q1How does the monotonic stack approach guarantee O(n) time for the Shifted Path Weight problem?
Each array index is pushed onto the stack exactly once and popped at most once. The while loop that pops indices only runs when a smaller element is found, so the total number of stack operations across the entire array is bounded by 2n, leading to linear time.
Q2What would happen if you used a non‑strict comparison (<=) instead of a strict one (<) when popping from the stack?
Using <= would treat equal heights as smaller, causing the algorithm to incorrectly shrink the subarray boundaries and potentially miss larger valid subarrays. It can also lead to duplicate processing of equal elements, breaking the O(n) guarantee.
Q3In a distributed system where each node holds a segment of the array, how could you compute the global maximum shifted path weight efficiently?
Each node can locally compute the maximum for its segment using the stack method, also returning the leftmost and rightmost boundary heights. Then, a merge step considers cross‑segment subarrays by treating the boundary heights as potential minima and combining the local maxima, similar to a parallel reduction of histogram rectangles.
Examples
Input
nums = [2, 1, 5, 6, 2]
Output
10
Explanation: Consider the subarray [2, 1, 5, 6, 2]. Length = 5, Min = 1, Product = 5. Consider [5, 6]. Length = 2, Min = 5, Product = 10. Consider [6]. Length = 1, Min = 6, Product = 6. Consider [2, 1, 5, 6]. Length = 4, Min = 1, Product = 4. The maximum product is 10.
Input
nums = [3, 3, 3, 3]
Output
12
Explanation: The entire array [3, 3, 3, 3] has length 4 and minimum value 3. Product = 4 * 3 = 12. Any smaller subarray will have a smaller length and the same minimum, resulting in a smaller product. Thus, the maximum is 12.
Input
nums = [1, 2, 3, 4, 5]
Output
9
Explanation: Subarray [1, 2, 3]: Len=3, Min=1, Prod=3. Subarray [2, 3, 4]: Len=3, Min=2, Prod=6. Subarray [3, 4, 5]: Len=3, Min=3, Prod=9. Subarray [4, 5]: Len=2, Min=4, Prod=8. Subarray [5]: Len=1, Min=5, Prod=5. The maximum is 9.
Input
nums = [-1, -2, -3]
Output
-1
Explanation: Subarray [-1]: Len=1, Min=-1, Prod=-1. Subarray [-2]: Len=1, Min=-2, Prod=-2. Subarray [-3]: Len=1, Min=-3, Prod=-3. Subarray [-1, -2]: Len=2, Min=-2, Prod=-4. Subarray [-2, -3]: Len=2, Min=-3, Prod=-6. Subarray [-1, -2, -3]: Len=3, Min=-3, Prod=-9. The maximum value among these is -1.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- The answer is guaranteed to fit in a 64-bit integer.
Optimal Approach & Strategy
Use a monotonic increasing stack to find, for each index, the nearest smaller element on the left and right. The width of the subarray where the current element is the minimum is rightIndex - leftIndex - 1, and the product of this width and the element’s value gives a candidate answer. This runs in O(n) time and O(n) space.
Brute Force Approach
Check every possible subarray, compute its minimum weight, multiply by its length, and track the maximum. This takes O(n^2) time and constant extra space.
Verified Code Solutions
function solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}class Solution {
public:
int solution(vector<int> nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
};class Solution {
public int solution(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
}def solution(nums):
sum = 0
for num in nums:
sum += num
return sumfunction solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}Asked in Top Tech Interviews
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.