欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實(shí)現(xiàn)LeetCode(121.買(mǎi)賣(mài)股票的最佳時(shí)間)

 更新時(shí)間:2021年07月26日 15:01:26   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(121.買(mǎi)賣(mài)股票的最佳時(shí)間),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 121.Best Time to Buy and Sell Stock 買(mǎi)賣(mài)股票的最佳時(shí)間

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.

這道題相當(dāng)簡(jiǎn)單,感覺(jué)達(dá)不到Medium的難度,只需要遍歷一次數(shù)組,用一個(gè)變量記錄遍歷過(guò)數(shù)中的最小值,然后每次計(jì)算當(dāng)前值和這個(gè)最小值之間的差值最為利潤(rùn),然后每次選較大的利潤(rùn)來(lái)更新。當(dāng)遍歷完成后當(dāng)前利潤(rùn)即為所求,代碼如下:

C++ 解法:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0, buy = INT_MAX;
        for (int price : prices) {
            buy = min(buy, price);
            res = max(res, price - buy);
        }
        return res;
    }
};

Java 解法:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0, buy = Integer.MAX_VALUE;
        for (int price : prices) {
            buy = Math.min(buy, price);
            res = Math.max(res, price - buy);
        }
        return res;
    }
}

類(lèi)似題目:

Best Time to Buy and Sell Stock with Cooldown

Best Time to Buy and Sell Stock IV

Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock II

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(121.買(mǎi)賣(mài)股票的最佳時(shí)間)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)買(mǎi)賣(mài)股票的最佳時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論