leetcode-121-Best-Time-to-Buy-and-Sell-Stock

描述


Say you have an array for which the $i^{th}$ element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

1
2
3
4
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example

1
2
3
4
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

分析


题目大意是给出一个数组,第 i 个元素代表第 i 天的价格,进行一次交易,求最大利润。可以抽象为,求 max(A[j]-A[i]),0<i<j<n
可以用两个变量,也记录当前最小的价格,一个记录当前的价格,一次遍历,随时更新最大利润,时间复杂度为 O(n)

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0) {
return 0;
}
int result = 0;
int now_min = prices[0];

for(int i = 1; i < prices.size(); i++) {
now_min = min(now_min, prices[i]);
result = max(result, prices[i]-now_min);
}
return result;
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
result = 0
now_min = prices[0]

for i in range(1, len(prices)):
now_min = min(now_min, prices[i])
result = max(result, prices[i]-now_min)
return result

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
func maxProfit(prices []int) int {
minValue := math.MaxInt64
result := 0
for i := 0; i < len(prices); i++ {
if prices[i] < minValue {
minValue = prices[i]
} else if prices[i] - minValue > result {
result = prices[i] - minValue
}
}
return result
}

相关问题


题目来源