解题思路:
动态规划
方法一:常规解法
class Solution {
public int bestTiming(int[] prices) {
int n = prices.length;
if (n == 0) return 0;
int[] dp = new int[n];
int cost = prices[0];
for (int i = 1; i < n; i++) {
cost = Math.min(cost, prices[i]);
dp[i] = Math.max(dp[i-1], prices[i] - cost);
}
return dp[n-1];
}
}
方法二:优化解法
class Solution {
public int bestTiming(int[] prices) {
int cost = Integer.MAX_VALUE, profit = 0;
for(int price : prices) {
cost = Math.min(cost, price);
profit = Math.max(profit, price - cost);
}
return profit;
}
}