Say you have an array for which the ith element is the price of a given stock on day I.
If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.
Original question link: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Question: Suppose you have an array where the I element represents the given I-day stock price.
If you are allowed to complete at most one transaction (for example, buy and sell one stock), design an algorithm to find the maximum profit.
The most naive solution is to traverse all the backend and locate the minimum value. Timeout.
public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int max = 0;for(int i=0;i<len;i++){for(int j=i+1;j<len;j++){int profit = prices[j] - prices[i];if(max < profit)max = profit;}}return max;}
The following method is much easier. First, assign the value of the first element to the minimum, and calculate the profit in turn. Each time you compare it with the maximum value, and save the new maximum value and the new minimum value.
public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int min = prices[0],max = 0;for(int i=1;i<len;i++){int profit = prices[i] - min;if(max < profit)max = profit;if(min > prices[i])min = prices[i];}return max;}