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 n=prices.length;
if(n<=1) return 0;
int maxProfit=0;
int maxPrice=prices[n-1];
for(int i=n-2;i>=0;i--){
maxPrice=Math.max(maxPrice,prices[i]);
maxProfit=Math.max(maxProfit,maxPrice-prices[i]);
}
return maxProfit;
}
}
本文介绍了一个算法,用于在给定的股票价格数组中,仅通过一次买入和卖出操作,找到可以获得的最大利润。
681

被折叠的 条评论
为什么被折叠?



