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) {
if(prices.length==0){
return 0;
}
int maxProfit=0;
int minPrice=prices[0];
for(int i=1;i<prices.length;i++){
minPrice=Math.min(minPrice,prices[i]);
maxProfit=Math.max(prices[i]-minPrice,maxProfit);
}
return maxProfit;
}
}