Leetcode_121_Best Time to Buy and Sell Stock

时间:2022-04-28 21:30:27

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43024967


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.


思路:

(1)题意为给定一个数组,数组中第i个元素的值对应着第i天的股票,求只进行一次交易,即买入一次并卖出,所能得到的最大利润。

(2)该题考查的是最大差值。对于本题,如果第i天的值大于第i+1天的值,呈现单调递减就不能买;只有第i天的值小于第i+1天的值,呈现单调递增时买才能获利。所以,遍历数组,分别比较其中相邻的元素之差,获得的最大值即为最大利润。

(3)希望本文对你有所帮助。


算法代码实现如下:

	/**
	 * @authod liqq
	 */
	public int maxProfit(int[] prices) {
		int len = prices.length;
		if (prices == null || len <= 1)
			return 0;
		int curr = prices[0];
		int profit = 0;
		for (int i = 0; i < len; i++) {
			int nex = prices[i];
			profit = nex - curr > profit ? nex - curr : profit;
			curr = curr < nex ? curr : nex;
		}
		return profit;
	}