2022年7月23日 星期六

121. Best Time to Buy and Sell Stock

給你一組數列prices,是每天股票的價錢,計算只買賣一次時可從中獲得的最大利潤,若無法獲利回傳 0

https://leetcode.com/problems/search-in-rotated-sorted-array/

範例
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: 在第二天時買入(price = 1),第五天時賣出(price = 6),可以獲得最大的利潤。
總左到右逐步數字探討,並有條件的記錄歷程中最大值與最小值

會遇到兩種狀況

  1. 新的數字比先前的最大值還要大,表示遇到新的高點,可以將最大值替換。
  2. 新的數字比先前的最小值還要小,表示遇到新的低點,但未來還不確定否獲利,因此可先將先前的獲利先記錄,再刷新最大值與最小值往後作業。

最後跑完數列後,再回傳最大的獲利即為答案

public int maxProfit(int[] prices) {

	//最大值最小值設為第一個數字
	int max = prices[0];
	int min = prices[0];
	int answer = 0;

	for (int a = 1; a < prices.length; a++) {
		//碰到的數字比較大,遇到本次新高點,值接替換最大值
		if (prices[a] > max) {
			max = prices[a];
		}

		if (prices[a] < min) {
			// 後方數字碰到比前者出現還小的,重新尋找新的低點
			if (answer < max - min) {
				//與歷史獲利紀錄比較,比較大則替換
				answer = max - min;
			}
			//刷新最大值、最小值
			max = prices[a];
			min = prices[a];
		}
	}
	
	//最後再與歷史獲利紀錄比較,比較大則替換
	if (answer < max - min) {
		answer = max - min;
	}
	return answer;
}

沒有留言:

張貼留言