121. Best Time to Buy and Sell Stock

121. 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Think and method:
In this case, although the application background is complicated, we really only need to find the maximum difference between two Numbers in a given array

I. Law of violence
Obviously, this is another problem that can be solved by the violence method. After contacting enough algorithm problems, we realize that the two for loops can be solved for similar extremum finding problems. For each group of I and J, we only need to find Max (price[I]-price[J]).

Time complexity: O(n^2)
Space complexity: O(1)

Ⅱ. dynamic programming
From the time complexity of method one we can see that this is not a very efficient method, the double for loop inevitably takes a lot of time to do some optimization.
Considering the problem, the idea must be to solve all the problems with only one for loop. In the process of analyzing the problem, the author finds that the idea of dealing with the problem is very close to “dynamic programming”, so dynamic programming is used to illustrate this method.
We consider to use a single variable to record the lowest price in history. If we want to get the maximum profit, we definitely want to buy it when the price is the lowest. Then, the profit from selling stocks every day is the price-min of the day
So after going through this over and over again, we can easily get a maximum, which is obviously the highest profit.

Time complexity: O(n)
Space complexity: O(1)

In the search for other methods, the author referred to some ideas of sharing, but in the end, the implementation is still the same ideas, but still put in the code for sharing.

Code:
1、

func maxProfit(prices []int) int {
	if len(prices) <= 1 {
		return 0
	}
	//find max
	var profit = prices[1] - prices[0]
	for i := 0; i < len(prices); i++ {
		for j := i + 1; j < len(prices); j++ {
			max := prices[j] - prices[i]
			if profit < max {
				profit = max
			}
		}
	}
	if profit < 0 {
		return 0
	}
	return profit
}


2、
第一版

func maxProfit(prices []int) int {

	if len(prices) <= 1 {
		return 0
	}
	buy := prices[0]
      maxpro := 0

      for i:=1 ; i <= len(prices)-1 ; i++{
		// buy
		buymin := min(buy,prices[i])
		// sell
		sell := max(-buy+prices[i],maxpro)
	    maxpro = sell
        buy = buymin
        }
	return maxpro
}
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

略微的简化

func maxProfit(prices []int) int {
	if len(prices) <= 1 {
		return 0
	}

	minprice := prices[0]
	max := 0
	for i := 0; i <= len(prices)-1; i++ {
        //refresh the max profit
		if prices[i]- minprice > max {
			max = prices[i] - minprice
		}
        //refresh the min price
		if prices[i] < minprice {
			minprice = prices[i]
		}
	}
	return max
}

Test:
Example 1:

Input: [7,1,5,3,6,4]
Output: 5
在这里插入图片描述

Example 2:

Input: [7,6,4,3,1]
在这里插入图片描述

Special Example :
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值