• 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;
        }
    };
    
  • 相关阅读:
    linux常用命令笔记
    head first html与css
    多线程编程核心技术日记
    nio
    排序算法
    随笔
    数据库读写分离
    购物网站设计
    http
    servlet初始化
  • 原文地址:https://www.cnblogs.com/xgbt/p/13022592.html
Copyright © 2020-2023  润新知