题目链接:
力扣https://leetcode-cn.com/problems/sum-of-subarray-ranges/
【分析】目前我想到的是通过两层循环,遍历的时候记住当前的最大值和最小值,然后累加最大值的最小值的差。虽然复杂度位O(n),但是也能过。
class Solution {
public long subArrayRanges(int[] nums) {
int n = nums.length, i, j;
long ans = 0;
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for(i = 0; i < n; i++){
max = min = nums[i];
for(j = i + 1; j < n; j++){
min = Math.min(min, nums[j]);
max = Math.max(max, nums[j]);
ans += max - min;
}
}
return ans;
}
}