Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mahale harsh patch 2 #1583

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/algorithms/math/least-common-multiple/leastCommonMultiple.js
Original file line number Diff line number Diff line change
@@ -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);
}
Original file line number Diff line number Diff line change
@@ -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;