题目描述:
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).
读题:
1.某样货物每天的动态价格,设计算法来求出能够获得的最大的利润。(不要求计算具体交易顺序)
2.每天都可以买卖,但是要先卖了才能买。
知识储备:
贪心算法
定义:
贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,只做出在某种意义上的局部最优解。贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。
解题思路:
1. 按照贪心算法,第二天只要能够盈利,就卖掉现货,获得利润。
2. 假设我昨天买入,今天会出现两种情况:
2.1 今天价格上涨了;于是马上卖出,获得利润,然后我可以重新买入,买入价=今天的价格
2.2 今天价格下降了;这时候不能卖出,假装我昨天没买,是今天才买入的。买入价=今天的价格。
提交代码:
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) {
return 0;
}
int profit = 0;
int price = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] > price) {
profit += prices[i]-price;
}
price = prices[i];
}
return profit;
}
}