Stock Buy Sell to Maximize Profit
The problem of stock buy sell to maximize profit involves finding the maximum profit that can be obtained by buying and selling a stock in a given array of stock prices. The problem assumes that the stock can be bought and sold only once, and that the selling price must be greater than the buying price.
public static int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
int profit = prices[i] - minPrice;
maxProfit = Math.max(maxProfit, profit);
}
return maxProfit;
}
This implementation iterates over the array of stock prices and maintains two variables: minPrice
, which represents the minimum price seen so far, and maxProfit
, which represents the maximum profit that can be obtained so far. For each price in the array, the algorithm updates minPrice
if the price is smaller than the current minimum, and updates maxProfit
if the difference between the current price and the current minimum is greater than the current maximum profit. At the end of the iteration, the algorithm returns maxProfit
, which represents the maximum profit that can be obtained by buying and selling the stock.
For example, let's consider the following array of stock prices:
int[] prices = {7, 1, 5, 3, 6, 4};
int maxProfit = maxProfit(prices);
System.out.println("Maximum profit: " + maxProfit);
// Maximum profit: 5
This means that the maximum profit that can be obtained by buying and selling the stock in the given array is 5, which is achieved by buying at a price of 1 and selling at a price of 6.