Identifying the Problem
We want to figure out the greatest possible profit from buying and selling a stock. The sequence of stock prices is represented by an array, and each element indicates the price on a particular day.

Starting with Basic Understanding
Initially, we might think that finding the maximum and minimum prices would suffice. However, the requirement that we must buy before selling adds a twist.
Realizing the Complexity
We realize that the order of prices matters, so the minimum price must occur before the maximum price.
Understanding the Challenge
The problem isn't as straightforward as finding the largest and smallest elements. Here's why:
- Buying before Selling Rule: We must buy before selling, so order matters. Simply finding
max
andmin
values is not enough; we need to ensure that themin
value comes before themax
.

Crafting the Solution
Given the constraint of buying before selling, we can sketch out a plan as follows:
Iterate Through Days: We'll iterate through each element (day) in the array.
Compare with Future Days: At each day, we'll check the difference between the price of that day and only the prices on days after it.
Nested Loops: This can be achieved with a simple nested for-loop.
- The first loop goes through all the days.
- At each day, a second loop (starting from
j = i + 1
) compares the price of the day to only the prices on subsequent days.
Maximize Profit: During the iteration, we'll keep track of the minimum price so far and the maximum profit obtainable. The difference between the current price and the minimum price will help us find the maximum profit.
Why This Approach Works
- Adheres to the Rule: By comparing a price only with prices on subsequent days, we ensure that buying occurs before selling.
- Efficiency: This approach leads to a solution within the given constraints.
xxxxxxxxxx
function stockOptimizer(prices) {
let maxDiff = 0;
for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
let newDiff = prices[j] - prices[i];
​
if (newDiff > maxDiff) {
maxDiff = newDiff;
}
}
}
​
return maxDiff;
}
​
console.log(stockOptimizer([2, 5, 15, 9]));