C++實(shí)現(xiàn)LeetCode(122.買(mǎi)股票的最佳時(shí)間之二)
[LeetCode] 122.Best Time to Buy and Sell Stock II 買(mǎi)股票的最佳時(shí)間之二
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
這道跟之前那道Best Time to Buy and Sell Stock 買(mǎi)賣(mài)股票的最佳時(shí)間很類(lèi)似,但都比較容易解答。這道題由于可以無(wú)限次買(mǎi)入和賣(mài)出。我們都知道炒股想掙錢(qián)當(dāng)然是低價(jià)買(mǎi)入高價(jià)拋出,那么這里我們只需要從第二天開(kāi)始,如果當(dāng)前價(jià)格比之前價(jià)格高,則把差值加入利潤(rùn)中,因?yàn)槲覀兛梢宰蛱熨I(mǎi)入,今日賣(mài)出,若明日價(jià)更高的話,還可以今日買(mǎi)入,明日再拋出。以此類(lèi)推,遍歷完整個(gè)數(shù)組后即可求得最大利潤(rùn)。代碼如下:
C++ 解法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, n = prices.size();
for (int i = 0; i < n - 1; ++i) {
if (prices[i] < prices[i + 1]) {
res += prices[i + 1] - prices[i];
}
}
return res;
}
};
Java 解法:
public class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 0; i < prices.length - 1; ++i) {
if (prices[i] < prices[i + 1]) {
res += prices[i + 1] - prices[i];
}
}
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
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(122.買(mǎi)股票的最佳時(shí)間之二)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)買(mǎi)股票的最佳時(shí)間之二內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(128.求最長(zhǎng)連續(xù)序列)
- C++實(shí)現(xiàn)LeetCode(126.詞語(yǔ)階梯之二)
- C++實(shí)現(xiàn)LeetCode(127.詞語(yǔ)階梯)
- C++實(shí)現(xiàn)LeetCode(124.求二叉樹(shù)的最大路徑和)
- C++實(shí)現(xiàn)LeetCode(123.買(mǎi)股票的最佳時(shí)間之三)
- C++實(shí)現(xiàn)LeetCode(121.買(mǎi)賣(mài)股票的最佳時(shí)間)
- C++實(shí)現(xiàn)LeetCode(119.楊輝三角之二)
- C++驗(yàn)證LeetCode包圍區(qū)域的DFS方法
相關(guān)文章
C語(yǔ)言深入分析遞歸函數(shù)的實(shí)現(xiàn)
遞歸(recursive)函數(shù)是“自己調(diào)用自己”的函數(shù),無(wú)論是采用直接或間接調(diào)用方式。間接遞歸意味著函數(shù)調(diào)用另一個(gè)函數(shù)(然后可能又調(diào)用第三個(gè)函數(shù)等),最后又調(diào)用第一個(gè)函數(shù)。因?yàn)楹瘮?shù)不可以一直不停地調(diào)用自己,所以遞歸函數(shù)一定具備結(jié)束條件2022-04-04
C++?OpenCV實(shí)戰(zhàn)之車(chē)道檢測(cè)
這篇文章主要介紹了基于C++?OpenCV實(shí)現(xiàn)的車(chē)道檢測(cè),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
C語(yǔ)言數(shù)據(jù)結(jié)構(gòu)之單向鏈表詳解
單向鏈表(單鏈表)是鏈表的一種,其特點(diǎn)是鏈表的鏈接方向是單向的,對(duì)鏈表的訪問(wèn)要通過(guò)順序讀取從頭部開(kāi)始。本文將為大家詳細(xì)講講單向鏈表的實(shí)現(xiàn)與使用,需要的可以參考一下2022-08-08
C語(yǔ)言中網(wǎng)絡(luò)地址與二進(jìn)制數(shù)之間轉(zhuǎn)換的函數(shù)小結(jié)
這篇文章主要介紹了C語(yǔ)言中網(wǎng)絡(luò)地址與二進(jìn)制數(shù)之間轉(zhuǎn)換的函數(shù)小結(jié),是C語(yǔ)言入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
對(duì)比C語(yǔ)言中memccpy()函數(shù)和memcpy()函數(shù)的用法
這篇文章主要介紹了對(duì)比C語(yǔ)言中memccpy()函數(shù)和memcpy()函數(shù)的用法,二者都是用于復(fù)制內(nèi)存內(nèi)容,注意區(qū)別,需要的朋友可以參考下2015-08-08

