LeetCode 121. Best Time to Buy and Sell Stock

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

Problem: https://leetcode.com/problems/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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

Thought:

from back to front, refresh the maximum price after prices[i] on each loop    O(n)

 

Code C++:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        if (prices.size() <= 1) {
            return profit;
        }
        
        int max_price = prices.back();
        for (int i = prices.size() - 2; i >= 0; i--) {
            if (prices[i] < max_price) {
                int diff = max_price - prices[i];
                profit = profit > diff ? profit : diff;
            }
            else {
                max_price = prices[i];
            }
        }
        return profit;
    }
};

 

以上是关于LeetCode 121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 121. Best Time to Buy and Sell Stock

Leetcode 121 Best Time to Buy and Sell Stock

LeetCode 121: Best Time to Buy and Sell Stock

LeetCode 121 Best Time to Buy and Sell Stock

Leetcode121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock leetcode解题笔记