Leetcode121. Best Time to Buy and Sell Stock | Two Pointers, Stack, DP

本文介绍了如何使用两种不同的算法——双指针和栈——来解决股票交易的最大利润问题。在给定的股票价格数组中,目标是找到购买和出售股票的最佳时机以获得最大利润。双指针法通过维护一个最低价格变量来找到最佳卖出价格,而栈法则利用栈保存历史最低价格。两种方法的时间复杂度均为O(n),空间复杂度分别为O(1)和O(n)。
摘要由CSDN通过智能技术生成

1.Description
There is an array named prices. prices[i] is the price of the given stock on the ith day. Our task is to miximize the profit by choosing the day to buy and sell the stock. The day to buy and the day to sell must be different. If there is no profit, return 0.
2.Algorithms I use
two pointers
stack
dynamic programming 这里
3.analysis&code
two pointers
If I sell the stock on the ith day, I must choose the day that is before the ith day and has the lowest price as the day to buy the stock to get the greatest profit. Hence, we can use two pointers. Pointer i iteraters through the array and Pointer cmin saves the smallest element(the lowest price before day i).For element i, the greatest profit of choosing day i as the day to sell stock must be the price of day i minus cmin. Then we choose the greatest one of all elements’ profit.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int cmin = 10001, ans = 0;
        for(int i = 0;i<prices.size();i++){
            cmin = min(cmin, prices[i]);
            ans = max(ans, prices[i]-cmin);
        }
        return ans;
    }
};

stack
The key idea of stack is the same as two pointers. The only difference is how the smallest element is stored. In two pointers, we use variable(or pointer) cmin to store the lowest price. Now we use stack to store it.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        stack<int> cmin;
        int ans = 0, tmp = 10001;
        cmin.push(tmp);
        for(int i = 0;i<prices.size();i++){
            if(prices[i] < cmin.top())
                cmin.push(prices[i]);
            else
                ans = max(ans, prices[i]-cmin.top());
        }
        return ans;
    }
};

4.Complexity
Time complexity: O(n)
Space complexity: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值