fork download
  1. /*
  2. Problem: Best Stock Trade with Buy and Sell Days
  3.  
  4. Return [buyDay, sellDay] for the most profitable single trade.
  5. The buy day must be before the sell day.
  6. For equal profits, prefer the earliest buy day, then the earliest sell day.
  7. Return [-1, -1] if no trade makes a positive profit.
  8.  
  9. Time: O(n)
  10. Auxiliary space: O(1)
  11. */
  12. // The strict < keeps the earliest day when buy prices tie.
  13. // The strict > keeps the first trade when profits tie.
  14. // That works for both tie rules because the candidate buy day can only stay the same
  15. // or move forward as you scan. A single-day input naturally returns [-1, -1] because the loop never run.
  16. function bestTradeIndices(prices) {
  17. let minPriceDay = 0;
  18. let maxProfit = 0;
  19. let buy = -1;
  20. let sell = -1;
  21.  
  22. for (let day = 1; day < prices.length; day++) {
  23. const profit = prices[day] - prices[minPriceDay];
  24.  
  25. if (profit > maxProfit) {
  26. maxProfit = profit;
  27. buy = minPriceDay;
  28. sell = day;
  29. }
  30.  
  31. if (prices[day] < prices[minPriceDay]) {
  32. minPriceDay = day;
  33. }
  34. }
  35.  
  36. return [buy, sell];
  37. }
  38.  
  39. function runTest(name, prices, expected) {
  40. const actual = bestTradeIndices(prices);
  41. const passed = actual[0] === expected[0] && actual[1] === expected[1];
  42.  
  43. console.log(
  44. `${passed ? "PASS" : "FAIL"} | ${name} | ` +
  45. `expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`
  46. );
  47. }
  48.  
  49. // 1. A cheaper price appears after day 0 - imp.
  50. runTest("Update the cheapest buy day", [7, 1, 5, 3, 6, 4], [1, 4]);
  51.  
  52. // 2. Equal buy prices and equal profits - imp.
  53. runTest("Keep the earliest buy and sell days", [1, 5, 1, 5], [0, 1]);
  54.  
  55. // 3. A new minimum leads to the same best profit - imp.
  56. runTest("Keep the earlier trade", [3, 7, 1, 5], [0, 1]);
  57.  
  58. // 4. No positive profit and a single-day input.
  59. runTest("Decreasing prices", [7, 6, 4, 3, 1], [-1, -1]);
  60. runTest("One day", [4], [-1, -1]);
Success #stdin #stdout 0.02s 5712KB
stdin
Standard input is empty
stdout
PASS | Update the cheapest buy day | expected [1,4], got [1,4]
PASS | Keep the earliest buy and sell days | expected [0,1], got [0,1]
PASS | Keep the earlier trade | expected [0,1], got [0,1]
PASS | Decreasing prices | expected [-1,-1], got [-1,-1]
PASS | One day | expected [-1,-1], got [-1,-1]