算法練習(42):Best Time to Buy and Sell Stock II

題意:給出一個數組,每個數代表當天股票的價格,有無數次買賣股票的機會,但是持有時不能買另一個。問最大收益。

分析與思路:這道題設計到波峯波谷的概念,有兩種思路。

1.可以每兩個相鄰的票價滿足有收益都買(貪婪算法)

2.只買最近的極小值,只賣當前極小值後最近的極大值。

代碼:

1.

class Solution {
public:
	int maxProfit(vector<int>& prices) {
		int sumPro = 0;
		for (int i = 1; i < prices.size(); i++) {
			if (prices[i] > prices[i - 1]) sumPro += prices[i] - prices[i - 1];
		}
		return sumPro;
	}
};

2.

class Solution {
public:
	int maxProfit(vector<int>& prices) {
		int valley = 0, peak = 0;
		int i = 0, sumPro = 0;
		while (i < prices.size()) {
			while (i + 1 < prices.size()&&prices[i] > prices[i + 1])i++;
			valley = prices[i];
			while (i + 1 < prices.size() && prices[i] < prices[i + 1]) i++;
			peak = prices[i];
			sumPro += (peak - valley);
			i++;
		}
		return sumPro;
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章