描述
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 | Input: [7, 1, 5, 3, 6, 4] |
Example
1 | Input: [7, 6, 4, 3, 1] |
分析
题目大意是给出一个数组,第 i 个元素代表第 i 天的价格,进行一次交易,求最大利润。可以抽象为,求 max(A[j]-A[i]),0<i<j<n
。
可以用两个变量,也记录当前最小的价格,一个记录当前的价格,一次遍历,随时更新最大利润,时间复杂度为 O(n)
解决方案1(C++)
1 | class Solution { |
解决方案2(Python)
1 | class Solution(object): |
解决方案3(Golang)
1 | func maxProfit(prices []int) int { |
相关问题
- (H) Best Time to Buy and Sell Stock IV
- (M) Best Time to Buy and Sell Stock II
- (M) Best Time to Buy and Sell Stock with Cooldown
- (M) Maximum Subarray
- (H) Best Time to Buy and Sell Stock III