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


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