题目
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 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。
限制:
0 <= 数组长度 <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
状态转移方程
第i天有两种状态,持有股票和不持有股票,持有股票的选择可以是卖或不卖,不持有只能不卖,因此状态转移方程定义为dp[i][0]第i天不持有股票情况下的手中的最大钱数,dp[i][1]表示第i天持有股票的情况下手中的最大钱数
dp[i][1]=Math.max(dp[i-1][1], (dp[i-1][0])-prices[i])
=Math.max(dp[i-1][1], -prices[i])
dp[i][0]=Math.max(dp[i-1][0], dp[i-1][1]+prices[i])
第i天持有股票可能是,第i-1天就持有,也可能是第i-1天不持有,第i天买的,就需要把手中的钱数减去当天的股价,反之亦然。因为只能交易一次,所以交易之前手里一定是没有钱的即dp[i-1][0]一定是0,
Base
由状态转移方程可知,最开始手里没钱
dp[0][0] = 0
dp[0][1]=-prices[0]
答案
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) {
return 0;
}
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0]=0;
dp[0][1]=-prices[0];
for (int i = 1; i < n; i++) {
dp[i][1]=Math.max(dp[i-1][1], -prices[i]);
dp[i][0]=Math.max(dp[i-1][0], dp[i-1][1]+prices[i]);
}
return dp[n-1][0];
}
}
一次遍历法
遍历到i时,用一个变量记住[0 ~ i-1]的最小值,同时记住结果
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
result = Math.max(result, prices[i]-min);
}
return result;
}
}