常见算法 - 股票交易设计以获取最大值

动态规划练习:

根据每天的股票价值,设计算法以获取最大值。要求每天只能进行一种操作,买、卖、等待,只有买了之后才能且进行卖,不能连续买,卖了之后的一天必须等待什么都不能做。


思路:来源leetcode讨论区。 s0代表当前状态未持有股票。s1当前状态持有股票。s2当前状态因卖出股票未持有股票,不同与s0。

enter image description here

There are three states, according to the action that you can take.

Hence, from there, you can now the profit at a state at time i as:

s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1

Then, you just find the maximum of s0[n] and s2[n], since they will be the maximum profit we need (No one can buy stock and left with more profit that sell right :) )

Define base case:

s0[0] = 0; // At the start, you don't have any stock if you just rest
s1[0] = -prices[0]; // After buy, you should have -prices[0] profit. Be positive!
s2[0] = INT_MIN; // Lower base case
class Solution {
    public int maxProfit(int[] prices) {
		if (prices.length <= 1) return 0;
                int n = prices.length;
		int[] s0 = new int[n];
		int[] s1 = new int[n];
		int[] s2 = new int[n];
		s1[0] = -prices[0];
		s0[0] = 0;
		s2[0] = Integer.MIN_VALUE;
		for (int i = 1; i < prices.length; i++) {
			s0[i] = Math.max(s0[i - 1], s2[i - 1]);
			s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i]);
			s2[i] = s1[i - 1] + prices[i];
		}
		return Math.max(s0[n - 1], s2[n - 1]);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值