diff --git a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js index 26a7681039..d8b8fe77eb 100644 --- a/src/algorithms/math/least-common-multiple/leastCommonMultiple.js +++ b/src/algorithms/math/least-common-multiple/leastCommonMultiple.js @@ -1,11 +1,12 @@ import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm'; /** - * @param {number} a - * @param {number} b - * @return {number} + * Finds the LCM of an array of numbers. + * @param {number[]} arr - Array of numbers + * @return {number} - LCM of the entire array */ +export default function leastCommonMultipleArray(arr) { + if (arr.length === 0) return 0; -export default function leastCommonMultiple(a, b) { - return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(a, b); + return arr.reduce((lcm, num) => leastCommonMultiple(lcm, num), 1); } diff --git a/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js b/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js index 9e244c89e1..b931757c1e 100644 --- a/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js +++ b/src/algorithms/uncategorized/best-time-to-buy-sell-stocks/accumulatorBestTimeToBuySellStocks.js @@ -1,20 +1,21 @@ /** * Finds the maximum profit from selling and buying the stocks. - * ACCUMULATOR APPROACH. + * Greedy approach to accumulate profit only on price increases. * * @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1] * @param {function(): void} visit - Visiting callback to calculate the number of iterations. * @return {number} - The maximum profit */ -const accumulatorBestTimeToBuySellStocks = (prices, visit = () => {}) => { - visit(); +const bestTimeToBuySellStocks = (prices, visit = () => {}) => { let profit = 0; - for (let day = 1; day < prices.length; day += 1) { + for (let day = 1; day < prices.length; day++) { visit(); - // Add the increase of the price from yesterday till today (if there was any) to the profit. - profit += Math.max(prices[day] - prices[day - 1], 0); + // Add only if today's price is higher than yesterday's + if (prices[day] > prices[day - 1]) { + profit += prices[day] - prices[day - 1]; + } } return profit; }; -export default accumulatorBestTimeToBuySellStocks; +export default bestTimeToBuySellStocks;