题目:
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.
分析:
枚举买的日期和卖的日期所需要的时间复杂度为O(n^2)。多设置一个变量min存放之前最小的价格,就可以把时间复杂度降低到O(n)。
Java代码实现:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int min = prices[0];
int profit = 0;
for(int i=1;i<prices.length;i++)
{
if(prices[i]<min)
min = prices[i];
profit = (prices[i]-min)>profit?(prices[i]-min):profit;
}
return profit;
}
}