`
hcx2013
  • 浏览: 88823 次
社区版块
存档分类
最新评论

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.

 

 

public class Solution {
    public int maxProfit(int[] prices) {
    	int min = Integer.MAX_VALUE;
    	int max = 0;
        for (int i = 0; i < prices.length; i++) {
			min = Math.min(min, prices[i]);
			max = Math.max(max, prices[i]-min);
        }
        return max;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics