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 Language Help.

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

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

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 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!

function maxProfitDays(stockPrices) {

let currentProfit = 0
let biggestProfit = 0;
let buyAndSellList = ;

for (let x = 0; x < stockPrices.length; x++){
for (let y = x; y < stockPrices.length; y++){

  currentProfit = stockPrices[y] - stockPrices[x];

  if (currentProfit >= biggestProfit){ 
    biggestProfit = currentProfit;
    buyAndSellList[0] = x;
    buyAndSellList[1] = y;
    
  }
}

}

return buyAndSellList;

}

const stockList = [17, 11, 60, 25, 150, 75, 2, 190];
maxProfitDays(stockList);

// Leave this so we can test your code:
module.exports = maxProfitDays;

function maxProfitDays(stockPrices) { return stockPrices .map((price, day) => { const future = stockPrices.slice(1 + day) const max = future.reduce((prev, x) => Math.max(prev, x), future[0]) return { profit: max - price, days: [day, future.indexOf(max) + day + 1] } }) .sort((a, b) => b.profit - a.profit)[0].days; } console.log(maxProfitDays([17, 11, 60, 25, 150, 10, 75, 31, 120])) // console.log(maxProfitDays([17, 16, 16, 16, 16, 16, 16, 16, 16])) // console.log(maxProfitDays([17, 123])) // Leave this so we can test your code: module.exports = maxProfitDays;
function maxProfitDays(stockPrices) { let maxDiff = 0; let days = []; for (let j in stockPrices) { for (let i in stockPrices){ if (j != i && j < i) { if (stockPrices[i]- stockPrices[j] > maxDiff) { maxDiff = stockPrices[i]- stockPrices[j]; days[0] = parseInt(j, 10); days[1] = parseInt(i, 10); } } } } return days; } // Leave this so we can test your code: module.exports = maxProfitDays;

I brute forced this one. I can optimize using a hash or map for the min and max values and make sure that the min day is before the max.

I might try to create a function to maximize profits with no restriction on the number of times you can buy and sell and return the profit.

Here is my function!

function maxProfitDays(stockPrices) {

let max = 0;
let maxIndex = 0;
let minIndex = 0;

for(i = 0; i < stockPrices.length; i++){
for(j = stockPrices.length; j > i; j–){
if(stockPrices[j] - stockPrices[i] > max){
max = stockPrices[j] - stockPrices[i];
maxIndex = i;
minIndex = j;

  }


}

}

return [maxIndex, minIndex];
}

// Leave this so we can test your code:
module.exports = maxProfitDays;

2 Likes

function maxProfitDays(stockPrices) {
let newA=0;
let newB=1;
for (let a=0;a<stockPrices.length-1;a++) {
for (let b=a+1;b<stockPrices.length;b++) {
if(stockPrices[b]-stockPrices[a]>stockPrices[newB]-stockPrices[newA]){
newA=a;
newB=b;
}
}
}
return [newA,newB];
}

// Leave this so we can test your code:
module.exports = maxProfitDays;

function maxProfitDays(stockPrices) {
let minPrice = Math.min(…stockPrices);
let maxPrice = Math.max(…stockPrices);
let maxProfit = 0
//Check possible easy solution with Math.min&.max methods
if(stockPrices.indexOf(minPrice)< stockPrices.indexOf(maxPrice))
{
return [stockPrices.indexOf(minPrice), stockPrices.indexOf(maxPrice)]
}
//If easy doesn’t work, go through every value and find maxProfit where lowest price is before higher price.
for(let i = 0; i < stockPrices.length; i++)
{
for(let j = i+1; j< stockPrices.length; j++)
{
if(stockPrices[j]-stockPrices[i] > maxProfit)
{
maxProfit = stockPrices[j]-stockPrices[i];
minPrice = stockPrices[i];
maxPrice = stockPrices[j];
}
}
}
return [stockPrices.indexOf(minPrice), stockPrices.indexOf(maxPrice)];
}

// Leave this so we can test your code:
module.exports = maxProfitDays;

Here’s a solution that only iterates once through the array. Nothing has been added for boundary conditions, (such as a continually decreasing array).

function maxProfitDays(stockPrices) {
var winningLowIndex = 0;
var winningHighIndex = 0;

var newLowIndex = 0;
var newHighIndex = 0 ;

var maxProfit = 0;

stockPrices.forEach ((v, i) => {
if (v < stockPrices[newLowIndex]) {
newLowIndex = i;
newHighIndex = i;
}
if (v > stockPrices[newHighIndex]) {
newHighIndex = i;
}

profit = stockPrices[newHighIndex] - stockPrices[newLowIndex];

if (profit > maxProfit) {
maxProfit = profit;
winningLowIndex = newLowIndex;
winningHighIndex = newHighIndex;
}

})

return ([winningLowIndex, winningHighIndex])

}

//console.log (maxProfitDays([17, 11, 60, 25, 150, 10, 148, 120]))
// Leave this so we can test your code:
module.exports = maxProfitDays;

function maxProfitDays(stockPrices) {
let buyIndex=0;
let sellIndex=0;
let maxDiff=0;
let arrayDiff=[ ];

for(let i=0;i<stockPrices.length;i++){
for(let d =i;d<stockPrices.length;d++){
arrayDiff.push([i,d,(stockPrices[d]-stockPrices[i])])
}
}

for(let x=1;x<arrayDiff.length;x++){

if(Number(arrayDiff[ x ][2])>maxDiff){
buyIndex=arrayDiff[ x ][0]
sellIndex=arrayDiff[ x ][1]
maxDiff=arrayDiff[ x ][2]
}
}

return [buyIndex,sellIndex]
}

maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120])

// Leave this so we can test your code:
module.exports = maxProfitDays;

function maxProfitDays(stockPrices) {
let buyIndex=0;
let sellIndex=0;
let maxDiff=0;
let arrayDiff=;

for(let i=0;i<stockPrices.length;i++){
let tmpSKprice = stockPrices[i];
for(let d =i;d<stockPrices.length;d++){
arrayDiff.push([i,d,(stockPrices[d]-stockPrices[i])])
}
}

for(let x=1;x<arrayDiff.length;x++){

if(Number(arrayDiff[2])>maxDiff){
buyIndex=arrayDiff[0]
sellIndex=arrayDiff[1]
maxDiff=arrayDiff[2]
}
}

return [buyIndex,sellIndex]
}

maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120])

// Leave this so we can test your code:
module.exports = maxProfitDays;

I did this challenge and noticed that all of the solutions here check for absolute differences between stock prices even though the profit is related to the relative stock prices.

Example 1

  • Price bought: 1
  • Price sold: 12
  • Profit: 12x the original investment

Example 2

  • Price bought: 2
  • Price sold: 20
  • Profit: 10x the original investment

So in fact you should use division “/” for comparing the prices to determine the biggest profit.

1 Like

function maxProfitDays(stockPrices) {
let buyAndSellDays = [0,0];
let highestDiff = 0;
stockPrices.forEach(price => {
for(let i = stockPrices.indexOf(price); i <= stockPrices.length; i++){
let difference = stockPrices[i] - price;
if(difference > highestDiff) {
highestDiff = difference;
buyAndSellDays = [stockPrices.indexOf(price), stockPrices.indexOf(stockPrices[i])]
};
};
});
return buyAndSellDays;
};

// Leave this so we can test your code:
module.exports = maxProfitDays;

function maxProfitDays(stockPrices) { let i, j, maxDiff = 0; let buySellPair = [0, 0]; for(i = 0 ; i < stockPrices.length ; i++){ for(j = ( i + 1 ) ; j < stockPrices.length ; j++ ){ if(stockPrices[j] > stockPrices[i]){ let diff = stockPrices[j] - stockPrices[i]; if (diff > maxDiff){ maxDiff = diff; buySellPair = [i , j]; } } } } return buySellPair; } console.log(maxProfitDays([120, 150, 17, 60, 25, 75, 31, 11])); // Leave this so we can test your code: module.exports = maxProfitDays;
1 Like

I seriously do not understand why this does not work

from random import seed from random import random import math import time seed(time.time() * 10) #This is the function def max_profit_days(stock_prices): array = [] for a1 in range(len(stock_prices) - 1): for a2 in range(a1 + 1, len(stock_prices)): array.append([stock_prices[a2] - stock_prices[a1], a1, a2]) array.sort() array = tuple(array) return [array[len(array) - 1][1], array[len(array) - 1][2]] arr = [ math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200), math.floor(random() * 200) ] print(arr) print(max_profit_days(arr))

That’s Python, not JavaScript.
The question asks for the function to return a tuple, not a list.
You have

    array = tuple(array)
    return [array[len(array) - 1][1], array[len(array) - 1][2]]

as the last 2 lines of the function,
but you would do:

    return (array[-1][1], array[-1][2])

to return a tuple instead.

HI,
This is my code… I tried with three different version but just pass one test…

function maxProfitDays(stockPrices) {
const max = Math.max(…stockPrices)
const min = Math.min(…stockPrices)

const maxi = stockPrices.indexOf(max)
const mini = stockPrices.indexOf(min)

return [mini, maxi]
}

console.log(maxProfitDays([17, 11, 60, 25, 150, 75, 31, 120]));

// Leave this so we can test your code:
module.exports = maxProfitDays;

any ideas about???

1 Like

I run your code on codecademy’s page and… It return [1,4] but the next message also…

Test cases

Tests failed to run due to an error: “”. Check your code and try again.

The same happened to me with other code… and the same result—

Any ideas???

1 Like

function maxProfitDays(stockPrices) {
let minValue=stockPrices[0];
let minPosition=0;
let maxValue=0;
let buyDay=0;
let sellDay=0;
for(let i=1;i<stockPrices.length;i++)
{
if(maxValue<stockPrices[i]-minValue){
maxValue=stockPrices[i]-minValue;
buyDay=minPosition;
sellDay=i;
}
if(stockPrices[i]<minValue)
{
minValue=stockPrices[i];
minPosition=i;
}
}

return [buyDay,sellDay];
}
// Leave this so we can test your code:
module.exports = maxProfitDays;

I think you have to take out the console.log stuff when you submit it so that it doesn’t give you an error.

Your stuff passed one test
because the max minus the min may mot give you the maximum profit
in a situation where the max is after the min (meaning the index of the max is more than the index of the min)
so I don’t know whether that strategy could work.