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.
注意,买入的日期一定是早于卖出的日期,所以遍历数组时,维护一个max代表收益,min记录当前最小值。
Source
public class Solution {
public int maxProfit(int[] prices) {
int max = 0, min = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++){
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}
}
Test
public static void main(String[] args){
int[] prices = {4,1,2,3};
int a = new Solution().maxProfit(prices);
System.out.println(a);
}