题目描述
给你一个下标从 0 开始的整数数组 nums
,该数组的大小为 n
,请你计算 nums[j] - nums[i]
能求得的 最大差值 ,其中 0 <= i < j < n
且 nums[i] < nums[j]
。
返回 最大差值 。如果不存在满足要求的 i
和 j
,返回 -1
。
示例 1:
输入:nums = [7,1,5,4]
输出:4
解释:
最大差值出现在 i = 1 且 j = 2 时,nums[j] - nums[i] = 5 - 1 = 4 。
注意,尽管 i = 1 且 j = 0 时 ,nums[j] - nums[i] = 7 - 1 = 6 > 4 ,但 i > j 不满足题面要求,所以 6 不是有效的答案。
示例 2:
输入:nums = [9,4,3,2]
输出:-1
解释:
不存在同时满足 i < j 和 nums[i] < nums[j] 这两个条件的 i, j 组合。
示例 3:
输入:nums = [1,5,2,10]
输出:9
解释:
最大差值出现在 i = 0 且 j = 3 时,nums[j] - nums[i] = 10 - 1 = 9 。
提示:
n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109
解法
方法一:维护前缀最小值
我们用变量 $mi$ 表示当前遍历到的元素中的最小值,用变量 $ans$ 表示最大差值,初始时 $mi$ 为 $+\infty$,而 $ans$ 为 $-1$。
遍历数组,对于当前遍历到的元素 $x$,如果 $x \gt mi$,则更新 $ans$ 为 $max(ans, x - mi)$,否则更新 $mi = x$。
遍历结束后,返回 $ans$。
时间复杂度 $O(n)$,其中 $n$ 为数组的长度。空间复杂度 $O(1)$。
| class Solution:
def maximumDifference(self, nums: List[int]) -> int:
mi = inf
ans = -1
for x in nums:
if x > mi:
ans = max(ans, x - mi)
else:
mi = x
return ans
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | class Solution {
public int maximumDifference(int[] nums) {
int mi = 1 << 30;
int ans = -1;
for (int x : nums) {
if (x > mi) {
ans = Math.max(ans, x - mi);
} else {
mi = x;
}
}
return ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | class Solution {
public:
int maximumDifference(vector<int>& nums) {
int mi = 1 << 30;
int ans = -1;
for (int& x : nums) {
if (x > mi) {
ans = max(ans, x - mi);
} else {
mi = x;
}
}
return ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12 | func maximumDifference(nums []int) int {
mi := 1 << 30
ans := -1
for _, x := range nums {
if mi < x {
ans = max(ans, x-mi)
} else {
mi = x
}
}
return ans
}
|
| function maximumDifference(nums: number[]): number {
const n = nums.length;
let min = nums[0];
let res = -1;
for (let i = 1; i < n; i++) {
res = Math.max(res, nums[i] - min);
min = Math.min(min, nums[i]);
}
return res === 0 ? -1 : res;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | impl Solution {
pub fn maximum_difference(nums: Vec<i32>) -> i32 {
let mut min = nums[0];
let mut res = -1;
for i in 1..nums.len() {
res = res.max(nums[i] - min);
min = min.min(nums[i]);
}
match res {
0 => -1,
_ => res,
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | /**
* @param {number[]} nums
* @return {number}
*/
var maximumDifference = function (nums) {
let mi = 1 << 30;
let ans = -1;
for (const x of nums) {
if (mi < x) {
ans = Math.max(ans, x - mi);
} else {
mi = x;
}
}
return ans;
};
|