150-買賣股票的最佳時機 II
假設有一個數組,它的第i個元素是一個給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你可以完成盡可能多的交易(多次買賣股票)。然而,你不能同時參與多個交易(你必須在再次購買前出售股票)。
樣例
給出一個數組樣例[2,1,2,0,1], 返回 2
標簽
數組 貪心 枚舉法
思路
使用貪心算法,只要可以產生利潤(后一天比前一天股票價值上升),就進行一次買賣
code
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
int size = prices.size();
if(size <= 0) {
return 0;
}
int max = 0;
for(int i=1; i<size; i++) {
if(prices[i] - prices[i-1] > 0) {
max += (prices[i] - prices[i-1]);
}
}
return max;
}
};