xinyu04

导航

LeetCode 121 Best Time to Buy and Sell Stock 贪心

You are given an array prices where prices[i] is the price of a given stock on the \(i\)th day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return \(0\).

Solution

很简单的贪心策略,遍历的时候维护一个最小值即可,然后更新最大的 \(prices[i]-\min\)

点击查看代码
class Solution {
private:
    int Min = 100000;
    int ans = -1;
public:
    int maxProfit(vector<int>& prices) {
       int n = prices.size();
        if(n==1)return 0;
        int Min = min(Min, prices[0]);
        for(int i=1;i<n;i++){
            Min = min(Min, prices[i]);
            ans = max(ans, prices[i]-Min);
        }
        if(ans==-1)return 0;
        else return ans;
    }
};

posted on 2022-07-20 03:26  Blackzxy  阅读(18)  评论(0编辑  收藏  举报