题目:
题解:贪心算法
代码:贪心算法
public class lc_122 {
public static int maxProfit(int[] prices) {
int res = 0;
// 扫描一遍,只要后一天比前一天大,就把这两天的差值加一下
// 贪心,今天比昨天大,就记录差值
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
public static void main(String[] args) {
int prices1[] = {7, 1, 5, 3, 6, 4};
int profit1 = maxProfit(prices1);
System.out.println(profit1);
int prices2[] = {1, 2, 3, 4, 5};
int profit2 = maxProfit(prices2);
System.out.println(profit2);
int prices3[] = {7, 6, 4, 3, 1};
int profit3 = maxProfit(prices3);
System.out.println(profit3);
}
}