LeetCode: The Best Time to Buy and Sell Stocks

Table of contents

topic

example

train of thought

the code

appendix


topic

Given an array prices, its i-th element prices[i] represents the price of a given stock on the i-th day.

You can only choose to buy the stock on one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.

Returns the maximum profit you can make from this trade. If you can't make any profit, return 0.

example

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (stock price = 1), sell on day 5 (stock price = 6), Maximum profit = 6-1 = 5.
     Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.
Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no trades are completed, so the maximum profit is 0.

train of thought

At first, you will find that buying and selling are two variables and both are unknown; after understanding, you will find that you don’t need to know the specific value, you only need to ensure the minimum purchase before, and compare the returns, and take the largest return.

the code

func maxProfit(prices []int) int {
	m,p := math.MaxInt32,0
	for i:=0;i<len(prices);i++{
		if prices[i] > m{
			p = max(prices[i]-m,p)
		}
		m = min(prices[i],m)
	}
	return p
}
func max(a,b int)int{
	if a > b{
		return a
	}
	return b
}
func min(a,b int)int{
	if a > b{
		return b
	}
	return a
}

appendix

The interview is a two-way relationship, there is no distinction between the two.

Guess you like

Origin blog.csdn.net/qq_34417408/article/details/125050597