Files
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

2.0 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6a19dd69388e5a6e59e4f2ef Challenge 326: Max Profit 28 challenge-326

--description--

Given an array of daily stock prices and a budget (in dollars), calculate the maximum profit you could make by buying and selling the stock over the given period.

  • You may only sell after you buy.
  • You may perform at most one buy and one sell transaction. Once you sell, you cannot buy again.
  • You can only buy whole shares.
  • Return the maximum possible profit as a string, rounded down to the nearest cent and formatted to two decimal places.

--hints--

getMaxProfit([5, 6], 50) should return "10.00".

assert.equal(getMaxProfit([5, 6], 50), "10.00");

getMaxProfit([8, 2, 5, 10], 20) should return "80.00".

assert.equal(getMaxProfit([8, 2, 5, 10], 20), "80.00");

getMaxProfit([4, 5, 3, 6], 20) should return "18.00".

assert.equal(getMaxProfit([4, 5, 3, 6], 20), "18.00");

getMaxProfit([54.40, 51.22, 53.99, 50.28, 53.01, 52.84], 200) should return "8.31".

assert.equal(getMaxProfit([54.40, 51.22, 53.99, 50.28, 53.01, 52.84], 200), "8.31");

getMaxProfit([15.38, 15.01, 14.99, 14.62, 14.28], 80) should return "0.00".

assert.equal(getMaxProfit([15.38, 15.01, 14.99, 14.62, 14.28], 80), "0.00");

getMaxProfit([121.45, 126.82, 122.91, 124.65, 128.83, 128.83, 127.33], 1230.25) should return "73.80".

assert.equal(getMaxProfit([121.45, 126.82, 122.91, 124.65, 128.83, 128.83, 127.33], 1230.25), "73.80");

--seed--

--seed-contents--

function getMaxProfit(prices, budget) {

  return prices;
}

--solutions--

function getMaxProfit(prices, budget) {
  let maxProfit = 0;

  for (let buy = 0; buy < prices.length - 1; buy++) {
    for (let sell = buy + 1; sell < prices.length; sell++) {
      const shares = Math.floor(budget / prices[buy]);
      const profit = shares * (prices[sell] - prices[buy]);
      if (profit > maxProfit) maxProfit = profit;
    }
  }

  return (Math.floor(maxProfit * 100) / 100).toFixed(2);
}