题目描述
Say you have an array for which the i th 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.
code:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 1)
return 0;
int max = 0;
int min = prices[0];
for(int i = 0 ; i < prices.length ; i++)
{
min = Math.min(min,prices[i]);
max = Math.max(max,prices[i]-min);
}
return max;
}
}Be cautious that it should have the initial value, not just zero.
本文介绍了一种寻找股票交易中最大利润的算法实现。通过一次遍历数组的方式找到买入和卖出的最佳时机,确保只进行一次交易的情况下获得最大收益。
350

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



