`
huntfor
  • 浏览: 201305 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Best Time to Buy and Sell Stock

 
阅读更多

新博文地址:[leetcode]Best Time to Buy and Sell Stock

这道题在2014年蘑菇街实习生招聘笔试中出现过,当时木有做出来。。。而且好多人都木有做出来。。。。现在看来逻辑还是很简单的,简单的一维DP,DP哎。。(╯‵□′)╯︵┻━┻

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.

 题目是说,如果你能回到过去,知道连续n天的股价,只能买卖一次,如何保证获益最大

    public int maxProfit(int[] prices) {
		if(prices == null || prices.length == 0){
			return 0;
		}
		int low = prices[0];
		int max = 0;
		for(int i = 0; i < prices.length; i++){
			if(prices[i] < low){
				low = prices[i];
			}
			if(prices[i] - low >= max){
				max = prices[i] - low;
			}
		}
		return max;		
    }

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics