[LeetCode ] Best Time to Buy and Sell Stock系列题解

这一系列的题目的基本模型是给出n天每天股票的价格,可以在任意一天买股票,在之后的任意一天把股票卖出,赚取差价,限制是手中最多有一张股票,必选把手中的股票卖掉才能再买股票。求最大获利。

题目1:Best Time to Buy and Sell Stock

这是最简单的一道题,在基本模型的基础上添加了一个限制条件,最多交易一次。

我们从第一天开始遍历,维护一个已经遍历过的股票的最小价格minPrice,答案为max(prices[ i ] - minPrice)。

Java代码:

class Solution {
     public int maxProfit(int[] prices) {
		 if(prices.length == 0) return 0;
		 int res,minPrice;
		 res = 0;
		 minPrice = prices[0];
		 for(int i = 1; i < prices.length; i++) {
			 res = Math.max(res, prices[i] - minPrice);
			 minPrice = Math.min(minPrice, prices[i]);
		 }
		 return res;
	 }
}

题目2: Best Time to Buy and Sell Stock II

在基本模型的基础上,交易的次数不受限制。

既然交易的次数不受限制,我们可以贪心的来思考了,只要第i天股票的价格大于第i-1天的股票价格,我们就进行交易,这样最后得到的结果肯定是最优的。

Java代码:

class Solution {
   public int maxProfit(int[] prices) {
		 if(prices.length == 0) return 0;
		 int res;
		 res = 0;
		 for(int i = 1; i < prices.length; i++) {
			 if(prices[i] > prices[i - 1]) {
				 res += prices[i] - prices[i - 1];
			 }
		 }
		 return res;
	 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值