JavaScript Challenge - Maximize Stock Trading Profit

This community-built FAQ covers the “Maximize Stock Trading Profit” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Maximize Stock Trading Profit

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

At first i thought it was as simple as to detect the lower and higher stock price in a “stockPrices” array and return the pair. Silly me, i then realized that the function should sell AFTER buying, so it should ignore high prices at the beginning and low prices at the end of the array haha.

It was a pretty entertaining project.

function maxProfitDays(stockPrices) { const detectBestDayToSell = (i, priceList) => { let higherPrice = priceList[i]; let day = i; for (let j = i++; j < priceList.length; j++) { if (priceList[j] > higherPrice) { higherPrice = priceList[j]; day = j } } return day } let bestDaysToBuyNSell = []; let bestProfit = 0; for (let buyDay = 0; buyDay < stockPrices.length; buyDay++) { const bestDayToSell = detectBestDayToSell(buyDay, stockPrices); const profit = stockPrices[bestDayToSell] - stockPrices[buyDay]; if (profit > bestProfit) { bestProfit = profit; bestDaysToBuyNSell = [buyDay, bestDayToSell]; } } return bestDaysToBuyNSell } // Testing const list = [120, 150, 17, 60, 25, 75, 31, 11]; console.log(maxProfitDays(list));

Here is my brute force solution by running 2 loops one on the day to buy the the second on the day to sell, by keeping day to sell after day to buy. it’s O(n^2).

function maxProfitDays(stockPrices) { let profit = 0; let buyDay; //the day we buy let sellDay; //the day we sell // loop day to buy i from day 0 to last day in the array for (let i=0; i<stockPrices.length; i++) { // loop day to sell from day i+1 to last day in the array for (let j=i+1; j<stockPrices.length; j++) { //test whether the profit on the 2 days is higher than the maximum previous profit if (stockPrices[j]-stockPrices[i] > profit) { profit = stockPrices[j]-stockPrices[i]; buyDay = i; sellDay = j; } } } return [buyDay,sellDay]; }; console.log(maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120]))

A more optimal code with only one loop and 2 pointers: one starting from the beginning and one from the end. it’s an O(N). Please let me know what you think. I tested it on random lists of 500 elements, it gives the same result as the standard code, but i didn’t see any difference in computation time.

function maxProfitDays(stockPrices) { let buyDay; //the day we buy let sellDay; //the day we sell let min = stockPrices[0]; let max = stockPrices[stockPrices.length-1]; let i=0; let j = stockPrices.length-1; while (i<=j) { if (stockPrices[i] <= min) { min = stockPrices[i]; buyDay = i; i++; } else if (stockPrices[i] <= max) {i++}; if (stockPrices[j] >=max) { max = stockPrices[j]; sellDay = j; j--; } else if (stockPrices[j] >=min) {j--} if (stockPrices[i]> max && stockPrices[j] < min) { if (stockPrices[i] -min>= max-stockPrices[j]) {j--} else {i++}; } } return [buyDay,sellDay]; }; console.log(maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120]))
1 Like

I really enjoyed this challenge.

Tested it too with some lists and it works fine. I’ll leave the explicit version just because i don’t like else statments that much, but regardless your code is so nice.

function maxProfitDays(stockPrices) { let buyDay; let sellDay; let i = 0; let j = stockPrices.length - 1; let min = stockPrices[i]; let max = stockPrices[j]; while (i <= j) { if (stockPrices[i] <= min) { min = stockPrices[i]; buyDay = i; i++ } if (stockPrices[i] > min && stockPrices[i] <= max) { i++ } if (stockPrices[j] >= max) { max = stockPrices[j]; sellDay = j; j-- } if (stockPrices[j] >= min) { j-- } if (stockPrices[i] > max && stockPrices[j] < min) { if (stockPrices[i] - min >= max - stockPrices[j]) { j-- } if (stockPrices[i] - min < max - stockPrices[j]) { i++ } } } return [buyDay,sellDay] }; console.log(maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120]));

function maxProfitDays(n) {
let max = n[0];
let maxIndex = 0;
let min = n[0];
let minIndex = 0;
for (let j = 0; j < n.length; j++) {
if (n[j] > max) {
max = n[j];
maxIndex = j;
}
}
for (let i = 0; i<maxIndex; i++) {
if (n[i] < min) {
min = n[i];
minIndex = i;
}
}
return [minIndex, maxIndex];
}
////// I only get 3/5 test passed and i really dont know why, any help as to whats wrong ?? thanks in advance!!

I think the issue is that the index of the maximum could be less than the index of the minimum, so that’s potentially an answer that’s not viable.
The trickier thing is to find the maximum difference between a value at an index, and another value at a greater index (representing the sale say being after the buy day).

Hi Guys. For some reason I have tried several times my code with different arrray arrangements to check everything was fine but the tester keeps telling me there is an error. Dunno, by now, this is my answer. If someone may know where i might have an error, please comment.

function maxProfitDays(stockPrices) { let parCompraVenta = [0, 0]; let mapped = stockPrices.map(function(el, i) { return { index: i, value: el }; }); mapped.sort(function(a, b) { if (a.value > b.value) { return 1; } if (a.value < b.value) { return -1; } return 0; }); let j = 0; let maxDiff = 0; mapped.forEach(pair =>{ while(j < stockPrices.length - 1){ if(mapped[j+1].index > pair.index){ if(mapped[j+1].value - pair.value > maxDiff){ maxDiff = mapped[j+1].value - pair.value; parCompraVenta = [pair.index, mapped[j+1].index]; } } j++; } }); return parCompraVenta; } console.log(maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120])); // Leave this so we can test your code: module.exports = maxProfitDays;

Something similar happened to me. How did you check how many test you passed?