Here is the interview question prompt, presented for reference.
This is a classic technical interview question that I've seen a number of times in real life interviews. Let's say you're given an array of stock prices, with each element being an integer that represents a price in dollars.
[ 10, 7, 6, 2, 9, 4 ]
Each index of the array represents a single day, and the the element at that index is the stock price for that given day. This means that the array below represents:
prices = [ 10, 7, 6, 2, 9, 4 ]
# Day 0 - a price of `$10`
# Day 1 - `$7`
# Day 2 - `$6` (and so on...)
int[] prices = {10, 7, 6, 2, 9, 4};
// Day 0 - a price of `$10`
// Day 1 - `$7`
// Day 2 - `$6` (and so on...)
let prices = [10, 7, 6, 2, 9, 4];
// Day 0 - a price of `$10`
// Day 1 - `$7`
// Day 2 - `$6` (and so on...)
int prices[]{ 10, 7, 6, 2, 9, 4 };
// Day 0 - a price of `$10`
// Day 1 - `$7`
// Day 2 - `$6` (and so on...)
int[] prices = {10, 7, 6, 2, 9, 4};
// Day 0 - a price of `$10`
// Day 1 - `$7`
// Day 2 - `$6` (and so on...)
var prices = []int{10, 7, 6, 2, 9, 4}
/* Day 0 - a price of `$10`
Day 1 - `$7`
Day 2 - `$6` (and so on...) */
Given the ability to only buy once and sell once, our goal is to maximize the amount of profit (selling price - purchase price) that we can attain and return that value. Note the only caveat is that that we cannot sell a stock before we buy it, which is important in identifying a solution.
Can you write a stock optimizer method called stockOptimizer
? See the following examples for further clarification:
stockOptimizer([ 10, 7, 6, 2, 9, 4 ])
# 7
stockOptimizer(new int[] {10, 7, 6, 2, 9, 4});
// 7
stockOptimizer([10, 7, 6, 2, 9, 4]);
// 7
stockOptimizer({10, 7, 6, 2, 9, 4});
// 7
StockOptimizer(new int[]{10, 7, 6, 2, 9, 4});
// 7
stockOptimizer([]int{10, 7, 6, 2, 9, 4})
// 7
For the above example, the max profit is made when we buy on day/index 3
(when the price is 2
) and sell on day/index 4
(when the price is 9
). 9 - 2
gives us 7
, which is returned by the function. Let's do another example.
stockOptimizer([9, 8, 6, 5, 3])
# 0
stockOptimizer(new int[]{9, 8, 6, 5, 3});
// 0
stockOptimizer([9, 8, 6, 5, 3]);
// 0
stockOptimizer({9, 8, 6, 5, 3});
// 0
stockOptimizer(new int[]{9, 8, 6, 5, 3});
// 0
stockOptimizer([]int{9, 8, 6, 5, 3})
// 0
From a quick glance, it seems like there's enough price differences to generate a profit. However, notice that the price drops every day, and thus we can't have a profit since we're required to buy before selling.
100000
0
)2147483647
O(n)
O(1)
1
elementYou can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Stock Buy and Sell Optimization.
public static int stockOptimizer(int[] prices) {
int buyIdx = 0;
int best = Integer.MIN_VALUE;
for (int i = 1; i < prices.length; i++) {
best = Math.max(best, prices[i] - prices[buyIdx]);
if (prices[i] < prices[buyIdx]) {
buyIdx = i;
}
}
return best;
}