股票问题,经典动态规划
/**
* 动态规划,用数组
* Runtime: 3 ms, faster than 25.53%
* Memory Usage: 55 MB, less than 25.36%
*/
class Solution {
public int maxProfit(int[] prices) {
int[] dp = new int[prices.length];
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
min = Math.min(min, prices[i]);
dp[i] = Math.max(dp[i - 1], prices[i] - min);
}
return dp[prices.length - 1];
}
}
/**
* 动态规划,不用数组
* Runtime: 2 ms, faster than 65.98%
* Memory Usage: 52 MB, less than 71.07%
*/
class Solution {
public int maxProfit(int[] prices) {
int min = prices[0], res = 0;
for (int i = 1; i < prices.length; i++) { // 或者用for (int price : prices),跑出来效果一模一样
min = Math.min(min, prices[i]);
res = Math.max(res, prices[i] - min);
}
return res;
}
}