本文主要是介绍[LeetCode] 901. Online Stock Span,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题: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;elseres =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);*/
这篇关于[LeetCode] 901. Online Stock Span的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!