2016. Maximum Difference Between Increasing Elements(Easy)

这篇博客介绍了两种算法实现寻找整数数组中满足条件的最大差值。第一种方法通过维护已遍历的最小值,第二种方法利用单调栈,动态更新栈底,找到最大差值。当最大差值小于等于0时返回-1。这两种高效的方法对于给定的整数数组问题提供了有效的解决方案。
摘要由CSDN通过智能技术生成
  1. 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值