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) {
// Start typing your Java solution below
// DO NOT write main() function
if(prices==null || prices.length<2) {
return 0;
}
int min = prices[0];
int maxGap = 0;
for(int p : prices) {
maxGap = Math.max(maxGap, p-min);
min = Math.min(min, p);
}
return maxGap;
}
}
没有评论:
发表评论