Overview
You are given an array of integers, which represents the price of a stock over time.
[10, 7, 5, 8, 11, 9]
The price may increase or decrease over time.
Your goal is to maximize profit, i.e. maximize the difference between the selling price and the buying price.
Therefore, you have two different decisions to make:
1. When to buy the stock,
2. When to sell it.
You must buy the stock exactly once, and must sell it exactly once (which must be after you buy it).
In the example above, the best time to buy would be "5" and the best time to sell would be "11", yielding a profit of "6".
Request
Create a function that will take in the array of prices and output the maximum profit that can be made for those prices.It is like https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ with catch that you must make 1 trasaction so if profit not possible make min loss.
In interview I got one pass solution for profit but could not get case where you should get minimum loss with 1 pass.
After interview I can only think of only BruteForce solution that can give me MaxProfit if possible else minimum loss.
Is there way to solve this with one pass.
class Solution{
public static int findProfit(int[] prices){
if(prices.length == 0){
return 0;
}
int cost = prices[0];
int profit = Integer.MIN_VALUE;
for(int i = 1; i<prices.length; i++){
cost = Math.min(cost, prices[i]);
profit = Math.max(profit, prices[i]-cost);
}
return profit;
}
public static int findProfitBF(int[] prices) {
int maxP = Integer.MIN_VALUE;
for(int i =0 ;i<prices.length-1; i++) {
for(int j = i+1; j <prices.length; j++) {
int t = prices[j] - prices[i];
if(t > maxP) {
maxP = t;
}
}
}
return maxP;
}
public static void main(String[] args) {
System.out.println(findProfit(new int[]{10, 7, 5, 8, 11, 9})); // ans 6
System.out.println(findProfitBF(new int[]{10, 7, 5, 4, 3, 1})); // ans -1
}
}