Best Time to Buy and Sell Stock

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.

//Time complexity O(n), auxiliary space O(1).

public int maxProfit(int[] prices) {

// Start typing your Java solution below
// DO NOT write main() function
int maxProfit = 0;
if(prices==null||prices.length ==0||prices.length==1)
return 0;

int minPrice = prices[0];
maxProfit = prices[1]-prices[0];
for(int i = 1;i<prices.length;i++)
{
if(prices[i]-minPrice>maxProfit)
{
maxProfit = prices[i]-minPrice;
}
if(prices[i]<minPrice)
minPrice=prices[i];
}

if(maxProfit>=0)
return maxProfit;
else return 0;
}

posted on 2013-05-17 16:22  Alan Yang  阅读(158)  评论(2编辑  收藏  举报