[LeetCode] 901. Online Stock Span

本文详细解析了LeetCode上的在线股票跨度问题,介绍了一种使用栈数据结构的高效解决方案,通过维护一个特殊的数据结构来快速计算当前元素的跨度,即最长连续子序列长度,其中所有元素都不大于当前元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题:https://leetcode.com/problems/online-stock-span/

题目大意

不断给出元素,求当前元素开始往前的最大子串,且串中每个元素的值都小于等于 该元素。

思路

class stockPair{
    int price;
    int day;
    public stockPair(int price,int day){
        this.price = price;
        this.day = day;
    }
}

class StockSpanner {
    Stack<stockPair> stack;
    int day;
    public StockSpanner() {
        stack = new Stack<>();
        day = 0;
    }
    
    public int next(int price) {
        day++;
        while(!stack.isEmpty() && stack.peek().price <= price){
            stack.pop();
        }
        int res;
        if(stack.isEmpty())
            res= day;
        else
            res =day - stack.peek().day;
        stack.add(new stockPair(price,day));
        return res;   
    }
}

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 */
class StockSpanner {
    Stack<int[]> stack = new Stack<>();

    public StockSpanner() {
    }

    public int next(int price) {
        int res = 1;
        while (!stack.isEmpty() && stack.peek()[0] <= price)
            res += stack.pop()[1];
        stack.push(new int[]{price, res});
        return res;
    }
}
/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner obj = new StockSpanner();
 * int param_1 = obj.next(price);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值