# 0121-买卖股票最佳时机(0121 – the best time to buy and sell stocks)-其他

## 0121-买卖股票最佳时机(0121 – the best time to buy and sell stocks)

1 <= prices.length <= 105
0 <= prices[i] <= 104

### python

``````# 0121.买卖股票最佳时机

# 贪心
class Solution:
def maxProfit(self, prices:[int]) -> int:
low = float("INF")
res = 0
for i in range(len(prices)):
low = min(low, prices[i])
res = max(res, prices[i]-low)
return res
``````

### golang

``````package greedy

import (
"fmt"
"math"
)

// 贪心算法
func maxProfit(prices []int) int {
low := math.MaxInt64
res := 0
for _,v := range prices {
low = min(low, v)
res = max(res, v-low)
}
return res
}

func min(a,b int) int {
if a > b {
return b
}
return a
}

func max(a,b int) int {
if a > b {
return a
}
return b
}

``````
————————

Given an array price, its second   I elements   Prices [i] represents the price of a given stock on day I.

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

Return the maximum profit you can make from this transaction. If you can’t make any profit, return 0.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: buy on day 2 (stock price = 1) and 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 can’t sell stocks before buying.
Example 2:

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

Tips:

1 <= prices.length <= 105
0 <= prices[i] <= 104

reference resources:

### python

``````# 0121.买卖股票最佳时机

# 贪心
class Solution:
def maxProfit(self, prices:[int]) -> int:
low = float("INF")
res = 0
for i in range(len(prices)):
low = min(low, prices[i])
res = max(res, prices[i]-low)
return res
``````

### golang

``````package greedy

import (
"fmt"
"math"
)

// 贪心算法
func maxProfit(prices []int) int {
low := math.MaxInt64
res := 0
for _,v := range prices {
low = min(low, v)
res = max(res, v-low)
}
return res
}

func min(a,b int) int {
if a > b {
return b
}
return a
}

func max(a,b int) int {
if a > b {
return a
}
return b
}

``````