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 sell
one share of the stock), design an algorithm to find the maximum profit.
通过一个循环比较当前元素和之前记录的最小元素的最大差值。
public class Solution {
public int maxProfit(int[] prices) {
int minElement=Integer.MAX_VALUE,dif=0;
for(int i=0;i<prices.length;i++){
dif=Math.max(dif, prices[i]-minElement);
minElement=Math.min(minElement, prices[i]);
}
return dif;
}
}