LeetCode_11:Best Time to Buy and Sell Stock II

1、总结:
  • 1、看solution2(解法三)中对while的灵活使用,使得代码一气呵成。我虽然明白这道题用波峰波谷的想法去破题,但是实现的却很粗糙,有一种武功招式没有跟上内功心法的赶脚(中二?)
  • 2、切记:学习算法根本目的是为了解决实际问题,所以锻炼思维很重要,实现方式也很重要!
  • 3、当我看到solution2的时候,我还在感慨代码实现的干净;当我看到solution3的时候又真实感受到了思维方式的魅力,有的时候换一种思路感觉世界都简单了。?学无止境~
2、题目:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

	Input: [1,2,3,4,5]
	Output: 4
	Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
	             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
	             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

	Input: [7,6,4,3,1]
	Output: 0
	Explanation: In this case, no transaction is done, i.e. max profit = 0.
3、我的解法:
	/**
	 * @param {number[]} prices
	 * @return {number}
	 */
	// 方法一:
	var maxProfit = function(prices) {
	    let tempBuy = prices[0];
	    let tempSell = 0;
	    let profit = 0;
	    for(let i = 1; i < prices.length; i++) {
	        if(prices[i] < prices[i-1]) {
	            if(tempSell > tempBuy) {             
	                profit += (tempSell - tempBuy);
									                // console.log('profit', profit);
									                // console.log('tempSell', tempSell);
									                // console.log('tempBuy', tempBuy);
	                tempSell = 0;
	            }       
	            tempBuy = prices[i];        
	        } else if (prices[i] >= prices[i-1]) {
	            tempSell = prices[i];
	            if(i == prices.length - 1) {                
	                profit += (tempSell - tempBuy);
									                // console.log('profit', profit);
									                // console.log('tempSell', tempSell);
									                // console.log('tempBuy', tempBuy);
	            }
	        }
	    }
	    return profit;
	};
4、其他解法
  • (1)目测像上一题一样可以循环遍历获得所有的组合及其总利润,从而暴力破解获得答案,但是效率不可能好。
    果然我按照solution中的解法一的递归实现了一遍,直接报超时:

      /**
       * @param {number[]} prices
       * @return {number}
       */
      // 解法二:		
      var calculate = function(prices, s) {
          if(s >= prices.length) {
              return 0;
          }
          let max = 0;
          for(let start = s; start < prices.length - 1; start++) {
              let maxProfit = 0;
              for(let end = start+1; end < prices.length; end++) {
                  if(prices[start] < prices[end]) {
                      let profit = calculate(prices, end+1) + prices[end] - prices[start];
                      if(profit > maxProfit) {
                          maxProfit = profit;
                      }
                  }
              }
              if(maxProfit > max) {
                  max = maxProfit;
              }
          }
          return max;
      }
      
      var maxProfit = function(prices) {
          return calculate(prices, 0);
      };
    

在这里插入图片描述
了解一下递归的思路然后放弃挣扎…

  • (2)solution2本质是找波峰波谷,但是感觉处理代码的手法比我自己实现更漂亮,尤其是while的运用很棒,我当时敲代码的时候,在if里面添加if其实有点难受,感觉就是在打补丁,没有solution2的实现来的一气呵成。
    所以重点学习solution2

      /**
       * @param {number[]} prices
       * @return {number}
       */
      // 解法三:	
      var maxProfit = function(prices) {
          let tempBuy = prices[0];
          let tempSell = prices[0];
          let maxProfit = 0;
          let i = 0;
          while(i < prices.length - 1) {
              while(i < prices.length - 1 && prices[i] >= prices[i+1]) {
                  i++;
              }
              tempBuy = prices[i];
              while(i < prices.length - 1 && prices[i] <= prices[i+1]) {
                  i++;
              }
              tempSell = prices[i];
              maxProfit += tempSell - tempBuy;
          }
          return maxProfit;
      };
    

效率倒是和方法一的效率没什么差别:
在这里插入图片描述

  • (3)solution3真的简单!!!比什么波峰波谷简单多了,而且效率还快!重点学什么solution2,别错过solution3才是真的!
    思路非常简单,累加所有正向收益即可!
    在这里插入图片描述

      // 解法四:	
      var maxProfit = function(prices) {
          let maxProfit = 0;
          for(let i = 1; i < prices.length; i++) {
              if(prices[i] > prices[i-1]) {
                  maxProfit += prices[i] - prices[i-1];
              }
          }
          return maxProfit;
      };
    

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值