2 Java explained Solutions[2ms]: Math and Mimic Stock Trading

  • 0
    • Question title is "Best Time to Buy and Sell", which is kind of misleading. What program actually need to return is the maximum profit.
    • In real world, intuitively, we buy on a day at low and sell on another day at high.
    • When we apply logic above into each single day, that is actually equal to day-trading. i.e. We only do day-trading if there's a positive gain. (Too good to be true in the real world, since we don't know next day's stock price..)
    • Solution 1:
    	int totalProfit = 0;
            for (int i = 1; i < prices.length; i++)
                int dailyGain = prices[i] - prices[i-1];
                if (dailyGain > 0) totalProfit += dailyGain;
            return totalProfit;
    • Solution 2: buy/sell when a trend breaks.
      • mimic right-side trade for selling - when stock price start to drop, sell
      • mimic left-side trade for buying - stop trailing down buy price when stock price goes up.
      • need to take profit for "rest of days" if there's no more trend-switch before end of the array.
    	int totalProfit = 0;
            if (prices.length == 0) return totalProfit;
            int buyPrice = prices[0];
            for (int i = 1; i < prices.length; i++) {
                if (prices[i] <= prices[i-1]) {
                    totalProfit += prices[i-1] - buyPrice; // take profit if stock start to drop
                    buyPrice = prices[i]; // trailing down the buy-dip point.
            int rest = prices[prices.length-1] - buyPrice;
            return rest > 0 ? totalProfit + rest : totalProfit;

Log in to reply

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