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;
        }
    };
    
  • 相关阅读:
    成功熬了四年还没死?一个IT屌丝创业者的深刻反思
    史氏语录
    WEB安全攻防学习内容
    从程序员的角度谈创业三年
    Windows2008 R2修改3389端口教程
    Win2008R2 zip格式mysql 安装与配置
    制作支持UEFI PC的Server2008 R2系统安装U盘
    郎科U208(主控 PS2251-50 HYNIX H27UCG8T2MYR)量产还原
    自用有线IP切换
    自动配置IP地址.bat
  • 原文地址:https://www.cnblogs.com/xgbt/p/13022592.html
Copyright © 2011-2022 走看看