zoukankan      html  css  js  c++  java
  • 121. Best Time to Buy and Sell Stock. 双端队列复习

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Note that you cannot sell a stock before you buy one.

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 5
    Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
      Not 7-1 = 6, as selling price needs to be larger than buying price.
    Example 2:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

    1.deque
    头部添加元素:deq.push_front(const T& x);
    末尾添加元素:deq.push_back(const T& x);
    任意位置插入一个元素:deq.insert(iterator it, const T& x);
    任意位置插入 n 个相同元素:deq.insert(iterator it, int n, const T& x);
    插入另一个向量的 [forst,last] 间的数据:deq.insert(iterator it, iterator first, iterator last);

    头部删除元素:deq.pop_front();
    末尾删除元素:deq.pop_back();
    任意位置删除一个元素:deq.erase(iterator it);
    删除 [first,last] 之间的元素:deq.erase(iterator first, iterator last);
    清空所有元素:deq.clear();

    下标访问:deq[1]; // 并不会检查是否越界
    访问第一个元素:deq.front();
    访问最后一个元素:deq.back();

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            deque <int> que;
            int ans = 0;
    
    
            for (int i=0;i<prices.size();i++){
                while (!que.empty() && prices[i] < que.back()){
                    que.pop_back();
                }
                if (!que.empty()){
                    ans = max( ans, prices[i] - que.front());
                }
                que.push_back(prices[i]);
            }
    
    
    
            return ans;
        }
    };
    
  • 相关阅读:
    html的基本框架和常用标签
    防火墙
    Zenmap
    每日一招:熟练掌握变盘方向
    每日一招:赚钱最快的选股策略
    操盘策略:黄金做单时间
    每日一招:坚守六大方式选出优质股
    如何保卫你的牛市胜利果实?
    名家看后市:长阴破位不必慌
    每日一招:补仓需遵守的技巧
  • 原文地址:https://www.cnblogs.com/xgbt/p/13022592.html
Copyright © 2011-2022 走看看