C++實現(xiàn)LeetCode(121.買賣股票的最佳時間)
[LeetCode] 121.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.
這道題相當簡單,感覺達不到Medium的難度,只需要遍歷一次數(shù)組,用一個變量記錄遍歷過數(shù)中的最小值,然后每次計算當前值和這個最小值之間的差值最為利潤,然后每次選較大的利潤來更新。當遍歷完成后當前利潤即為所求,代碼如下:
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;
}
}
類似題目:
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++實現(xiàn)LeetCode(121.買賣股票的最佳時間)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)買賣股票的最佳時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++非繼承時函數(shù)成員訪問屬性和類繼承過程中的訪問控制
這篇文章主要介紹了C++非繼承時函數(shù)成員訪問屬性和類繼承過程中的訪問控制,非繼承時,protected成員和private成員沒有任何區(qū)別,都是類內(nèi)部可以直接訪問它們、類外部的類對象不可訪問它們、類內(nèi)部的類對象可以訪問它們,更多詳細內(nèi)容請參考下面相關(guān)資料2022-03-03
C語言中的內(nèi)存管理之掌握動態(tài)分配的技巧(最新推薦)
在C語言編程中,內(nèi)存管理是一項至關(guān)重要的技能,它直接關(guān)系到程序的性能和穩(wěn)定性,特別是在處理大型數(shù)據(jù)集或需要靈活內(nèi)存布局的場景下,本文將深入探討C語言中的動態(tài)內(nèi)存分配技巧,幫助開發(fā)者更好地掌握這一核心技能2025-03-03

