- Maximum Difference Between Increasing Elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
1.维护一个最小值
class Solution {
public:
int maximumDifference(vector<int>& nums) {
//记录已遍历的最小值,用当前元素减去最小值,判断是否更新最大差值。同时更新最小值
int minv=nums[0],maxd=-1;
for(int x:nums){
maxd=max(maxd,x-minv);
minv=min(minv,x);
}
if(maxd<=0)
return -1;
return maxd;
}
};
2.维护一个单调递增的栈
注意:STL的stack类没有bottom这一属性,动态记录stack的bottom,当stack的size是1时,bottom=s.top()
当新元素加入时,需要保证栈中已有的元素都小于当前元素,可能的最大差值即新的栈顶元素-栈底元素
class Solution {
public:
int maximumDifference(vector<int>& nums) {
//维护一个单调递增的栈,最大差值即栈顶-栈底的差
stack<int>s;
int maxd=-1;
int bottom=nums[0];
for(int x:nums){
while(!s.empty() && x<s.top()){
s.pop();
}
s.push(x);
if(s.size()==1){
bottom=s.top();
}
maxd=max(maxd,s.top()-bottom);
}
if(maxd<=0){
return -1;
}
return maxd;
}
};