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.
這道題相當(dāng)簡單,感覺達不到Medium的難度,只需要遍歷一次數(shù)組,用一個變量記錄遍歷過數(shù)中的最小值,然后每次計算當(dāng)前值和這個最小值之間的差值最為利潤,然后每次選較大的利潤來更新。當(dāng)遍歷完成后當(dāng)前利潤即為所求,代碼如下:
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)文章
Ubuntu16.04下配置VScode的C/C++開發(fā)環(huán)境
這篇文章主要介紹了Ubuntu16.04下配置VScode的C/C++開發(fā)環(huán)境的教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03C++中用new創(chuàng)建二維數(shù)組和指針數(shù)組實例代碼
這篇文章主要介紹了C++中用new創(chuàng)建二維數(shù)組和指針數(shù)組實例代碼,非常不錯,具有參考借鑒價值,需要的朋友參考下2017-03-03Qt音視頻開發(fā)之音頻播放QAudioOutput的實現(xiàn)
這篇文章主要為大家詳細介紹了如何利用Qt實現(xiàn)音頻播放QAudioOutput功能,文中的示例代碼講解詳細,對我們學(xué)習(xí)Qt開發(fā)有一定的幫助,需要的可以參考一下2023-03-03C++開發(fā)在IOS環(huán)境下運行的LRUCache緩存功能
本文著重介紹如何在XCODE中,通過C++開發(fā)在IOS環(huán)境下運行的緩存功能。算法基于LRU,最近最少使用,需要的朋友可以參考下2012-11-11