剑指 Offer 63. 股票的最大利润
中等
361
相关企业
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
值得注意的点是:买入股票最晚是卖出股票当天,也就是,要先买入再卖出。
股票问题的三种解法,其实只有两种啦
第一种是我自己的第一想法,写得很啰嗦,时间复杂度、空间复杂度都是O(n),所以有很大的优化空间;
第二种是参考力扣K神的动态规划解法,写出的完整版(未经空间压缩);
基于第二种解法中动态规划依赖关系较为简单,可以进行空间压缩(用一个变量代替数组),得到第三种解法。
动态规划解法,主要考虑了,在第i
个位置处,达到最大利润有两种情况:
第一种:在第i
个位置处卖出股票,此时利润为nums[i]-numsMin[0...i-1]
;
第二种:在第i
个位置之前卖出股票,此时利润为dp[i-1]
;
public int maxProfit1(int[] prices) {
// help1[i], min of [0...i]
// help2[i], max of [i...n-1]
// res[i] = help2[i]-help1[i],
// max = max{res[i]|i=0...n-1}
int n=prices.length;
if(n==0) return 0;
int[] help1 = new int[prices.length];
int[] help2 = new int[prices.length];
int max=0;
help1[0]=prices[0];
for(int i=1;i<n;i++){
help1[i]=Math.min(help1[i-1],prices[i]);
}
help2[n-1]=prices[n-1];
for(int i=n-2;i>=0;i--){
help2[i]=Math.max(help2[i+1],prices[i]);
}
for(int i=0;i<n;i++){
max=Math.max(max,help2[i]-help1[i]);
}
return max;
}
public int maxProfit2(int[] prices) {
int n=prices.length;
if(n==0) return 0;
// dp[i], [0..i]maxProfit,
// two case,
// case1: sell at i, then profit is [i]-pricesMin[0...i-1]
// case2: sell it before i, then profit is dp[i-1]
int[] dp = new int[n];
dp[0]=0;
int cost=prices[0];
for(int i=1;i<n;i++){
dp[i]=Math.max(dp[i-1],prices[i]-cost);
cost=Math.min(cost,prices[i]);
}
return dp[n-1];
}
public int maxProfit(int[] prices) {
int n = prices.length;
if(n==0) return 0;
int cost=prices[0];
int res=0;
for(int i=1;i<n;i++){
res=Math.max(res,prices[i]-cost);
cost=Math.min(cost,prices[i]);
}
return res;
}
}