只要第一天买入,第二天卖出可以获得利润就可以买入,每一步的最优解合起来刚好就是全局最优解,即贪心算法
public class Test122 {
@Test
public void test() {
System.out.println(maxProfit(new int[] { 7, 1, 5, 3, 6, 4 }));
System.out.println(maxProfit(new int[] { 1, 2, 3, 4, 5 }));
System.out.println(maxProfit(new int[] { 7, 6, 4, 3, 1 }));
}
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int pre = prices[0];
int total = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > pre) {
total += (prices[i] - pre);
}
pre = prices[i];
}
return total;
}
}