Say you have an array for whichITh element is the price of a given stock on dayI.
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.
The problem is abstracted to find the maximum difference value of the array and satisfy the condition that the values are smaller, larger, and later.
First, I wrote the following code to test whether leetcode has strict time requirements:
public class Solution { public int maxProfit(int[] prices) { if(prices.length==0){ return 0; } int MaxProfit = 0; int len = prices.length; for(int i=0;i<len;i++){ for(int j=i+1;j<len;j++){ if(prices[j]-prices[i]>MaxProfit){ MaxProfit = prices[j]-prices[i]; } } } return MaxProfit; }}
No surprise, TLE.
In fact, a bit of thinking will find that the two cycles are a great waste of time. In fact, each time we only need to find the minimum value of the current position, if it is smaller than the minimum value, the minimum value will be updated; otherwise, the maximum difference value will be calculated.
public class Solution { public int maxProfit(int[] prices) { if(prices.length==0){ return 0; } int MaxProfit = 0; int len = prices.length; int Min = prices[0]; for(int i=1;i<len;i++){ if(prices[i]<Min){ Min = prices[i]; } else {if(prices[i]-Min>MaxProfit){MaxProfit = prices[i]-Min;}} } return MaxProfit; }}
Best time to buy and buy stock