122. Best Time to Buy and Sell Stock II

2018/04/08 leetcode 共 1057 字,约 4 分钟

Title

the problem link

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).

题目大意: 数组是每天的价格,买一个卖一个,计算最大收益,可以多次买卖。

Solution

第一个是峰谷峰值法,找个波谷,找个波峰来计算

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

第二种就是不管波峰波谷了

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

Search

    Table of Contents