作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
关键词:力扣,LeetCode,题解,清晰讲解,算法,增量,差值,Python, C++
目录
题目地址:https://leetcode-cn.com/problems/maximum-difference-between-increasing-elements/
题目描述
给你一个下标从 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
解题方法
方法一:暴力
可以寻找暴力法,即两重循环遍历所有的 i , j i ,j i,j,找到最大差值。
两重循环的时间复杂度是 O ( N 2 ) O(N^2) O(N2),题目给出的数据范围是 1000,计算一下总的循环此时是 1 0 6 10^6 106,可以通过力扣。
class Solution(object):
def maximumDifference(self, nums):
N = len(nums)
res = float("-inf")
for i in range(N):
for j in range(i + 1, N):
if nums[i] < nums[j]:
res = max(res, nums[j] - nums[i])
return -1 if res == float("-inf") else res
方法三:保留之前的最小值
我们注意到当遍历到某个位置 i i i 的时候,只需要记录在它之前的最小数值就行了。
因此我们使用一个变量,保存遇到的最小值。
时间复杂度是 O ( N ) O(N) O(N)。
class Solution(object):
def maximumDifference(self, nums):
N = len(nums)
prevMin = nums[0]
res = -1
for i in range(1, N):
if nums[i] > prevMin:
res = max(res, nums[i] - prevMin)
prevMin = min(prevMin, nums[i])
return res
日期
2022 年 2 月 26 日—— 愿一切都好