码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Best Time to Buy and Sell Stock

时间:2017-05-24 20:19:22      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:let   position   sha   mod   ret   style   并保存   base   bsp   

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.

原题链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

题目:如果你有一个数组,当中的第 i 个元素代表给定的第 i 天的股票价格。

假设你被同意至多完毕一个交易(如,买一和卖一股票)。设计一个算法找出最大的利润。

最Naive的解法,就是遍历全部的  后 - 前 ,找出最小值。超时了。

	public static int maxProfit(int[] prices){
		int len = prices.length;
		if(len <= 1)
			return 0;
		int max = 0;
		for(int i=0;i<len;i++){
			for(int j=i+1;j<len;j++){
				int profit = prices[j] - prices[i];
				if(max < profit)
					max = profit;
			}
		}
		return max;
	}

以下的方法就简便多了,首先赋首元素的值给最小,依次向后计算利润,每次与最大值比較并保存新的最大值和新的最小值。

	public static int maxProfit(int[] prices){
		int len = prices.length;
		if(len <= 1)
			return 0;
		int min = prices[0],max = 0;
		for(int i=1;i<len;i++){
			int profit = prices[i] - min;
			if(max < profit)
				max = profit;
			if(min > prices[i])
				min = prices[i];
		}
		return max;
	} 


LeetCode——Best Time to Buy and Sell Stock

标签:let   position   sha   mod   ret   style   并保存   base   bsp   

原文地址:http://www.cnblogs.com/yfceshi/p/6900691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!