Skip to content

Latest commit

 

History

History

2104

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.

Return the sum of all subarray ranges of nums.

A subarray is a contiguous non-empty sequence of elements within an array.

 

Example 1:

Input: nums = [1,2,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0 
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.

Example 2:

Input: nums = [1,3,3]
Output: 4
Explanation: The 6 subarrays of nums are the following:
[1], range = largest - smallest = 1 - 1 = 0
[3], range = 3 - 3 = 0
[3], range = 3 - 3 = 0
[1,3], range = 3 - 1 = 2
[3,3], range = 3 - 3 = 0
[1,3,3], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.

Example 3:

Input: nums = [4,-2,-3,4,1]
Output: 59
Explanation: The sum of all subarray ranges of nums is 59.

 

Constraints:

  • 1 <= nums.length <= 1000
  • -109 <= nums[i] <= 109

Similar Questions:

Solution 1. Brute Force

// OJ: https://leetcode.com/problems/sum-of-subarray-ranges/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
    long long subArrayRanges(vector<int>& A) {
        long long ans = 0, N = A.size();
        for (int i = 0; i < N; ++i) {
            int mn = A[i], mx = A[i];
            for (int j = i; j < N; ++j) {
                mn = min(mn, A[j]);
                mx = max(mx, A[j]);
                ans += mx - mn;
            }
        }
        return ans;
    }
};

Solution 2. Monotonic Stack

// OJ: https://leetcode.com/problems/sum-of-subarray-ranges/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    long long subArrayRanges(vector<int>& A) {
        long long ans = 0, N = A.size();
        vector<int> prevLE(N, -1), nextLT(N, N), prevGE(N, -1), nextGT(N, N);
        stack<int> ins, des;
        for (int i = 0; i < N; ++i) {
            while (ins.size() && A[ins.top()] > A[i]) {
                nextLT[ins.top()] = i;
                ins.pop();
            }
            if (ins.size()) prevLE[i] = ins.top();
            ins.push(i);
            while (des.size() && A[des.top()] < A[i]) {
                nextGT[des.top()] = i;
                des.pop();
            }
            if (des.size()) prevGE[i] = des.top();
            des.push(i);
        }
        for (long i = 0; i < N; ++i) ans += A[i] * ((i - prevGE[i]) * (nextGT[i] - i) - (i - prevLE[i]) * (nextLT[i] - i));
        return ans;
    }
};

TODO

https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624222/JavaC%2B%2BPython-O(n)-solution-detailed-explanation