第一种太简单不想写,第二种太难想不到。。。。。
第一种:没有什么考虑的写法
class Solution {
public int maxProfit(int[] prices) {
int low = Integer.MAX_VALUE;
int max = 0;
for(int i =0; i< prices.length; i++){
if(prices[i]<low){
low = prices[i];
}else if(prices[i]-low>max){
max = prices[i]-low;
}
}
return max;
}
}
//或者这么写
class Solution {
public int maxProfit(int[] prices) {
int low = Integer.MAX_VALUE;
int max = 0;
for(int i =0; i< prices.length; i++){
low = Math.min(prices[i], low);
max = Math.max(prices[i]-low,max);
}
return max;
}
}
第二种 动态规划
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int[] dp = new int[prices.length];
dp[0] = prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i] = (dp[i - 1] < prices[i]) ? dp[i - 1] : prices[i];
max = (prices[i] - dp[i]) > max ? prices[i] - dp[i] : max;
}
return max
}
}
文章介绍了两种计算股票交易中能获得最大利润的算法。第一种是基于循环的简单方法,通过比较当前价格和最低价格差来更新最大利润。第二种是使用动态规划,通过维护一个dp数组来优化计算过程。
509

被折叠的 条评论
为什么被折叠?



