题目:
Say you have an array prices
for which the i
t
h
^{th}
th element is the price of given stock on day 给定一个数组,它的第i个元素是一支给定股票第i天的价格。
Design an algorithm to find the maximun profit.You may complete as many transactions as you like(i.e.,buy one and sell one share of the stock multiple times).
设计一个算法来计算你所能获取的最大利润。你尽可能多的完成交易(多次买卖一支股票)。
Note:You may not engage in multiple transactions at the same time(i.e,You must sell the stock before you buy again).
注意:你不能同时参与多比交易(你必须在再次购买前出售掉之前的股票)。
示例一举例,
prince:[7,1,5,3,6,4]
priceSize:6
考虑在最后一天要不要进行卖?
(1)若不卖,则[7,1,5,3,6,4] ==> maxProfit(prices,6)
[7,1,5,3,6] ⇒ maxProfit(prices,5)
最后一天相当于不存在,可循环下去。
(2)若卖,(?,4)
[7,1,5,3,6] +[6,4] ==> maxProfit(prices, 5) + (4 - 6)
==>maxProfit([7,1,5,3,6,4],5) + (prices[5] - prices[4])
决定在i=4号买,5号买,则在[7,1,5,3,6]中还可以进行买卖
[7,1,5,3] +[3,4] ==> maxProfit(price, 4) + (4 - 3)
==>maxProfit([7,1,5,3,6,4],4) + (prices[5] - prices[3])
[7,1,5] + [5,4] ==> maxProfit(price, 3) + (4 - 5)
==>maxProfit([7,1,5,3,6,4],3) + (prices[5] - prices[2])
决定在i=3号买,5号买,则在[7,1,5]中还可以进行买卖,但[5,4]之间不能买
[7,1] +[1,4] ==> maxProfit(price, 2) + (4 - 1)
==>maxProfit([7,1,5,3,6,4],2) + (prices[5] - prices[1])
[7]+[7,4] ==> maxProfit(price, 1) + (4 - 7)
==>maxProfit([7,1,5,3,6,4],1) + (prices[5] - prices[0])
目标为计算这两种选择中的最大值
int maxProfit(int* prices, int pricesSize){
if (pricesSize <= 1) return 0; //边界条件,子问题的限制
int max = 0;
int profit;
//假设最后一天不卖
profit = maxProfit(prices, pricesSize - 1;)
if (profit > max){
max = profit
}
//假设最后一天要卖
for (int i = 1; i < pricesSize - 1; i++){
profit = maxProfit(prices, i) + prices[pricesSize - 1] - prices[i - 1]
if (profit > max){
max = profit;
}
}
return max;
}
int maxProfit(int* prices, int pricesSize){
if (pricesSize <= 1) return 0;
int profits[pricesSize+1]; // profits = maxProfit(prices, i)
profits[i] = 0;
for (int k = 2; k <= pricesSize; k++){
int profit;
int max = 0;
//(1)假设决定不卖
profit = profits[k-1];
if (profit > max) {
max = profit;
}
//(2)假设决定最后一天卖
for (int i = 1; i <= k-1; i++){
profit = profits[i] + prices[k-1] - prices[i-1];
if (profit > max){
max = profit;
}
}
profits[k] = max;
}
return profits[pricesSize]
}
方法二:
只看相邻的两天,若发现,今天便宜,明天贵则进行买卖
int maxProfit(int* prices, int pricesSize){
int total = 0;
for(int i = 0; i+1 < pricesSize; i++){
if (princes[i] < princes[i+1]){
total += prices[i+1] - prices[i]
}
}
return total;
}