【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,不需要特地用三目表达式判断
        
     }

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

猜你喜欢

转载自blog.csdn.net/chao_ji_cai/article/details/89279621