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 {
// keep track of min price & max profit
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0)
return 0;
int minprice = prices[0];
int maxprofit = 0;
for (int i = 1; i < prices.length; i++) {
int currprofit = prices[i] - minprice;
if (currprofit > maxprofit)
maxprofit = currprofit;
if (prices[i] < minprice)
minprice = prices[i];
}
return maxprofit;
}
}
股票买卖最大利润算法
318

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



