My 1ms Solution for 122. Best Time to Buy and Sell Stock II


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

  • 0
    B

    It's clear and efficient


  • 0
    A

    I feel confused about this requirement: you may not engage in multiple transactions at the same time(ie, you must sell the stock before you buy again). Does this mean you CAN sell and buy at the same day? For example, [1,2,3,4] is the price for day 0~3. So can we buy at 1 and sell at 2, then buy at 2 and sell at 3, then buy at 3 and sell at 4? I think your algorithm is somewhat like this, correct? p.s.: the runtime is 2ms.


  • 0
    L

    process1: buy at 1 and sell at 2,then buy at 2 and sell at 3,then buy at 3 and sell at 4
    process2: buy at 1 and sell at 4,ignore 2 and 3
    As we can see,process1 has the same outcome with process2.I think sell and buy at the same day is equal to ingore this day,and maybe he use this point.


  • 0
    B

    The question tell us that you can buy and sell the stock at the same time.The benefits come to you when you sell some stock.You sell ,you gain.But before you can sell the stock you have some stock.So when the stock you buy last day is cheaper than the one today,there is no benefit for you.So the tactics is selling when you gain and buying when you can gain.ps: my runtime is 1ms,it's real.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.