给你一个整数数组 nums
。nums
中,子数组的 范围 是子数组中最大元素和最小元素的差值。
返回 nums
中 所有 子数组范围的 和 。
子数组是数组中一个连续 非空 的元素序列。
示例 1:
输入:nums = [1,2,3] 输出:4 解释:nums 的 6 个子数组如下所示: [1],范围 = 最大 - 最小 = 1 - 1 = 0 [2],范围 = 2 - 2 = 0 [3],范围 = 3 - 3 = 0 [1,2],范围 = 2 - 1 = 1 [2,3],范围 = 3 - 2 = 1 [1,2,3],范围 = 3 - 1 = 2 所有范围的和是 0 + 0 + 0 + 1 + 1 + 2 = 4
示例 2:
输入:nums = [1,3,3] 输出:4 解释:nums 的 6 个子数组如下所示: [1],范围 = 最大 - 最小 = 1 - 1 = 0 [3],范围 = 3 - 3 = 0 [3],范围 = 3 - 3 = 0 [1,3],范围 = 3 - 1 = 2 [3,3],范围 = 3 - 3 = 0 [1,3,3],范围 = 3 - 1 = 2 所有范围的和是 0 + 0 + 0 + 2 + 0 + 2 = 4
示例 3:
输入:nums = [4,-2,-3,4,1] 输出:59 解释:nums 中所有子数组范围的和是 59
提示:
1 <= nums.length <= 1000
-109 <= nums[i] <= 109
暴力枚举。
循环遍历 i,作为子数组的起始位置。对于每个 i,遍历每个 j 作为子数组的终止位置,此过程中不断求解子数组的最大值、最小值,然后累加差值到结果 ans 中。
最后返回 ans 即可。
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(n - 1):
mi = mx = nums[i]
for j in range(i + 1, n):
mi = min(mi, nums[j])
mx = max(mx, nums[j])
ans += (mx - mi)
return ans
class Solution {
public long subArrayRanges(int[] nums) {
long ans = 0;
int n = nums.length;
for (int i = 0; i < n - 1; ++i) {
int mi = nums[i], mx = nums[i];
for (int j = i + 1; j < n; ++j) {
mi = Math.min(mi, nums[j]);
mx = Math.max(mx, nums[j]);
ans += (mx - mi);
}
}
return ans;
}
}
class Solution {
public:
long long subArrayRanges(vector<int>& nums) {
long long ans = 0;
int n = nums.size();
for (int i = 0; i < n - 1; ++i)
{
int mi = nums[i], mx = nums[i];
for (int j = i + 1; j < n; ++j)
{
mi = min(mi, nums[j]);
mx = max(mx, nums[j]);
ans += (mx - mi);
}
}
return ans;
}
};
func subArrayRanges(nums []int) int64 {
var ans int64
n := len(nums)
for i := 0; i < n-1; i++ {
mi, mx := nums[i], nums[i]
for j := i + 1; j < n; j++ {
mi = min(mi, nums[j])
mx = max(mx, nums[j])
ans += (int64)(mx - mi)
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}