javascript 最大利润

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 最大利润相关的知识,希望对你有一定的参考价值。

function getMaxProfit(stockPrices) {
  if (stockPrices.length < 2) {
    throw new Error("Getting a profit requires at least 2 prices");
  }
  // Calculate the max profit
  let max = stockPrices[1] - stockPrices[0];
  let minPrice = stockPrices[0];
  for (let i = 1; i < stockPrices.length; i++) {
    const currentPrice = stockPrices[i];
    const currentProfit = stockPrices[i] - minPrice;
    max = Math.max(max, currentProfit);
    minPrice = Math.min(minPrice, currentPrice);
  }

  return max;
}

// Tests

let desc = 'price goes up then down';
let actual = getMaxProfit([1, 5, 3, 2]);
let expected = 4;
assertEqual(actual, expected, desc);

desc = 'price goes down then up';
actual = getMaxProfit([7, 2, 8, 9]);
expected = 7;
assertEqual(actual, expected, desc);

desc = 'price goes up all day';
actual = getMaxProfit([1, 6, 7, 9]);
expected = 8;
assertEqual(actual, expected, desc);

desc = 'price goes down all day';
actual = getMaxProfit([9, 7, 4, 1]);
expected = -2;
assertEqual(actual, expected, desc);

desc = 'price stays the same all day';
actual = getMaxProfit([1, 1, 1, 1]);
expected = 0;
assertEqual(actual, expected, desc);

desc = 'error with empty prices';
const emptyArray = () => (getMaxProfit([]));
assertThrowsError(emptyArray, desc);

desc = 'error with one price';
const onePrice = () => (getMaxProfit([1]));
assertThrowsError(onePrice, desc);

function assertEqual(a, b, desc) {
  if (a === b) {
    console.log(`${desc} ... PASS`);
  } else {
    console.log(`${desc} ... FAIL: ${a} != ${b}`);
  }
}

function assertThrowsError(func, desc) {
  try {
    func();
    console.log(`${desc} ... FAIL`);
  } catch (e) {
    console.log(`${desc} ... PASS`);
  }
}

以上是关于javascript 最大利润的主要内容,如果未能解决你的问题,请参考以下文章

javascript 从数组中返回最大利润。

华为OD机试真题 JavaScript 实现最大利润2023 Q1 | 100分

华为OD机试真题 JavaScript 实现最大利润2023 Q1 | 100分

经典算法四:股票的最大利润(动态规划)

华为机试真题 C++ 实现最大利润2022.11 Q4 新题

股票的最大利润