leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.
Introduction to golang + algorithm I will solve it with go and Python to strengthen the brain. (Python is weak but experienced)
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.
Japanese translation
Suppose you have an array whose * i * th element is the price of a particular stock on the * i * day.
If you are allowed to complete only one transaction at most (that is, buy one and sell one share), design an algorithm to find the maximum profit.
Please note that you cannot sell your shares before you buy them.
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.
Initialize the variable that stores the maximum profit and the minimum value to search the entire array
Use min which turns in a loop and returns the smaller one and max which returns the larger one
The return value is max_profit, which is the maximum profit.
Answer code
def maxProfit(prices):
max_profit, min_price = 0, float('inf')
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
--I'll write it in Go too!
func maxProfit(prices []int) int {
if len(prices) == 0 {
return 0
}
max, lowest := 0, 0
for i := 1; i < len(prices); i++ {
if prices[i] < prices[lowest] {
lowest = i
} else if cur := prices[i] - prices[lowest]; cur > max {
max = cur
}
}
return max
}
Recommended Posts