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;
        }
    };
    
  • 相关阅读:
    Centos7安装配置JDK8
    Jmeter学习笔记
    mysql5.7版本免安装配置教程
    mysql查看线程详解(转载)
    xpath定位方法小结(转载)
    nginx负载均衡的5种策略(转载)
    loadrunner多场景的串行执行以及定时执行
    mysql 远程连接超时解决办法
    JAVA内存构成详解
    jconsole远程连接超时问题解决方法
  • 原文地址:https://www.cnblogs.com/xgbt/p/13022592.html
Copyright © 2011-2022 走看看