LeetCode122:購買股票的最佳時機II
阿新 • • 發佈:2018-12-09
解析:
該題和121不一樣之處就是可以買賣多次,但是難度沒有增加多少,基本的思路就是,低買高賣。如果i天的價格低於i+1天的價格且此時手裡沒有股票,則可以買進;如果第i天價格高於第i+1天,且手裡有股票,則可以賣出;如果第i天低於第i+1天,但是第i+1天是最後一天,則最後以一天賣出。把所有的差值計算出來,就是最大的利潤。
程式碼:
int maxProfit(vector<int>& prices) { int maxProfit = 0;//最大利潤 if (prices.empty()) return maxProfit; int days = prices.size(); bool buy = false;//手裡是否有股票的標記 int i; int buyPrice; for (i = 0; i < days - 1; i++) { if (prices[i + 1] > prices[i] && !buy) { buyPrice = prices[i]; buy = true; } else if ((prices[i + 1] < prices[i] ) && buy) { maxProfit += prices[i] - buyPrice; buy = false; } } if (i == days - 1 && buy)//最後一天,且手裡有股票 { maxProfit += prices[i] - buyPrice; buy = false; } return maxProfit; }
leetCode上有一種比較簡單的做法,就是用一個數組儲存,第i+1的值和第i個值的差,然後計算陣列中所有正數的和,即為最終的結果。
int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; vector<int> benefit; int result = 0; for (auto it = prices.begin(); it != prices.end()-1; it++) { benefit.push_back(*(it + 1) - *it); } for (auto a : benefit) { if (a > 0) result += a; } return result; }