【LeetCode-Java实现】121.Best Time to Buy and Sell Stock

121.Best Time to Buy and Sell Stock

题目描述

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

股票买入卖出规则:
(1)先买入,才能卖出(即buy要在sell之前),且至多只能买入和卖出一次;
(2)买入时价格比卖出时便宜,卖出-买入=获得的收益(题目就是问最大收益是多少)。
若前面的日期没有一个是比后面的日期便宜的(可以理解为prices数组是递减的),就不买入,收益直接就是0

解题思路

求最优解,这是个典型的动态规划题(DP)

  1. 定义一个代表当前最小元素的变量sofarMin作为买入时的价值(初始值假定为数组第一个元素);
  2. 遍历数组,
    遇到prices[i]比sofarMin大的,就卖出,收益=prices[i]-sofarMin;
    遇到prices[i]比sofarMin小的,说明这一天买入更加划算,所以将sofarMin更新为这一天的价值;
  3. 如果出现2中的第二种情况,就用新的sofarMin再次进入循环中,得出新的收益… …以此类推,将得到的所有收益进行比较,最大值即为所求的maxProfit

实现代码

根据上述思路可得Java代码:.

//动态规划
     public int maxProfit(int[] prices) {
    	 int maxProfit=0;          //最大收益初始值为0
    	 int sofarMin=prices[0];   //假设数组中第一个元素就是当前最小的元素     sofarMin:买入股票的价值
    	 
    	 for(int i=1;i<prices.length;i++) {  //向后遍历数组
    		 
    		 if(sofarMin<prices[i]) {     //如果后面元素> 当前最小元素 ,则在这天卖出股票。收益=当前遍历到的元素减去sofarMin
    			 /*
    			  * 注:这一行是动态规划过程,等会儿再看,先看下面那个判断语句
    			  * 执行完else语句-->新的sofarMin进入for循环,得出新的maxProfit
    			  * 比较这些maxProfit,其中最大的才是所需的最终答案
    			  */
    			 maxProfit=Math.max(maxProfit, prices[i]-sofarMin);     
    		 }                                                       
    		                                                         
    		 else {     
    			 sofarMin=prices[i];   //如果后面元素< 当前最小元素,就用这个元素代替当前最小元素,在这天买入石头---然后再重新进入循环
    		 } 
    		                                        
    	 }
    	 return maxProfit;   //因为上面maxProfit初始值为0,所以如果下面未符合判断条件的情况下,maxProfit仍然是0,不需要特地用三目表达式判断
        
     }

遇到这种求最优解问题,可以考虑使用动态规划解决,不过动态规划真不好理解,需要多做题总结才能慢慢掌握…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值