Loading

【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 ith 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.

dp_00 第i天 当前没有股票 状态是0

dp_01 第i天 当前持有股票 状态是1

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //经典的动态规划题目
        if(prices.size()==0) return 0;
        int dp_00=0;
        int dp_01=INT_MIN;
        for(auto it:prices)
        {
            dp_01=max(dp_01,-it);
            dp_00=max(dp_00,dp_01+it);

        }

        return dp_00;

    }
};

 

posted @ 2021-11-19 15:30  aalanwyr  阅读(41)  评论(0编辑  收藏  举报