标签:nums int Sum stk Ranges range subarray Subarray sum
原题链接在这里: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 Sum of Subarray Minimums 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 Stack<Integer> stk = 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 }
标签:nums,int,Sum,stk,Ranges,range,subarray,Subarray,sum 来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16392013.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。