现在的位置: 首页 > 综合 > 正文

Best Time to Buy and Sell Stock

2012年08月16日 ⁄ 综合 ⁄ 共 666字 ⁄ 字号 评论关闭

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;
}

抱歉!评论已关闭.