LeetCode 2104. Sum of Subarray Ranges
原题链接在这里:https://leetcode.com/problems/sum-of-subarray-ranges/
题目:
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
题解:
Find sum(max - min) in all the subarrays. It is equal to find sum(max) - sum(min) in all the subarrays.
Using the way in to find min and max of all the subarrays.
Time Complexity: O(n). n = nums.length.
Space: O(1).
AC Java:
1 class Solution { 2 public long subArrayRanges(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 Stackstk = new Stack<>(); 8 long sum = 0; 9 int n = nums.length; 10 for(int i = 0; i <= n; i++){ 11 while(!stk.isEmpty() && nums[stk.peek()] > (i == n ? Integer.MIN_VALUE : nums[i])){ 12 int minInd = stk.pop(); 13 int pre = stk.isEmpty() ? -1 : stk.peek(); 14 sum -= (long)nums[minInd] * (i - minInd) * (minInd - pre); 15 } 16 17 stk.push(i); 18 } 19 20 stk.clear(); 21 for(int i = 0; i <= n; i++){ 22 while(!stk.isEmpty() && nums[stk.peek()] < (i == n ? Integer.MAX_VALUE : nums[i])){ 23 int maxInd = stk.pop(); 24 int pre = stk.isEmpty() ? -1 : stk.peek(); 25 sum += (long)nums[maxInd] * (i - maxInd) * (maxInd - pre); 26 } 27 28 stk.push(i); 29 } 30 31 return sum; 32 } 33 }
类似.