首页 > 代码库 > LeetCode——Best Time to Buy and Sell Stock

LeetCode——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.

原题链接: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;
	}