记录一道非常有趣的动态规划问题
一、题目位置
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
二、解法
1. 暴力解法
public int maxProfit(int[] prices) {
if(prices == null) return 0;
// 状态:利润
// 选择:购股日期
// dp(n)定义:输入一个数字n代表购股日期,返回最大利润
int length = prices.length;
int [] dp = new int[length];
int res = 0;
// 遍历dp数组:
for(int j = 0;j < length - 1;j ++){
// dp状态转移方程式定义:
for(int i = j + 1;i < length;i ++){
dp[j] = Math.max(dp[j], prices[i] - prices[j]);
}
res = Math.max(dp[j],res);
}
return res;
}
2. 优化方案
public int maxProfit(int[] prices) {
if(prices == null) return 0;
// max代表利润最大值,min代表最小购股值
// prices[i] - min代表当前利润值
int min = prices[0], max = 0;
for(int i = 1;i < prices.length;i ++){
max = Math.max(max,prices[i] - min);
min = Math.min(min,prices[i]);
}
return max;
}