Topic:
Say you has an array for which the i-th element is the price of a given-stock on day I.
If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.
Ideas:
1. The goal is to find the difference in the array of two values (the maximum difference), if the large number after the small number
2. Iterate through the array, set a current min min (initially integer.max_value) and a maximum difference max (initialized to 0)
Update min at a time and update max (current element value-min)
public class Solution {public int maxprofit (int[] prices) { int len=prices.length; Array length int max=0; Maximum difference int min=integer.max_value; The current minimum value for (int i=0;i<len;i++) { if (prices[i]<min) min=prices[i]; if (Prices[i]-min>max) max=prices[i]-min; } return max;} }
121-best time to Buy and Sell Stock