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 min = Integer.MAX_VALUE;
int max = 0;
for (int i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i]-min);
}
return max;
}
}
本文介绍了一种用于计算股票交易中最大可能利润的算法。该算法仅允许进行一次买入和一次卖出操作,并通过迭代记录最低购买价格和最高潜在利润来找到最佳交易时机。
677

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



