问题-假设您有一个数组,其中ith
元素是给定股票在当日的价格i
。
如果只允许您最多完成一笔交易(即买入和卖出一股股票),请设计一种算法以找到最大的利润。
示例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.
示例2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
我相信可以使用动态编程来解决此问题,并且在继续进行解决之前,我尝试使用自己的方法来解决此问题。 我确实检查了蛮力算法,并意识到我的方法与蛮力并不相似
public class Solution {
public int maxProfit(int prices[]) {
int maxprofit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > maxprofit)
maxprofit = profit;
}
}
return maxprofit;
}
}
这是我的方法
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res=0
if not prices:
return 0
idx=prices.index(min(prices))
value=min(prices)
try:
for i in range (idx+1,len(prices)):
res=max(res,prices[i]-value)
except IndexError :
return 0
return res
我的代码通过了示例测试案例和143/200案例,但对于这一案例却失败了。
Input: [2,4,1]
Output: 0
Expected: 2
如何改善我的代码?如何使这种方法起作用?或者如果这种方法是完全错误的,请详细说明。
我相信我的方法的时间复杂度要比蛮力好,因此,要努力使此代码起作用;以后还要查看动态编程方法
答案 0 :(得分:3)
def max_profit(prices):
if not prices:
return 0
max_prof = 0
min_price = prices[0]
for i in range(1, len(prices)):
if prices[i] < min_price:
min_price = prices[i]
max_prof = max(max_prof, prices[i] - min_price)
return max_prof
输出:
print(max_profit([1, 2, 3, 4, 5]))
print(max_profit([5, 4, 3, 2, 1]))
print(max_profit([3, 1, 2, 4, 5]))
print(max_profit([7, 1, 5, 3, 6, 4]))
print(max_profit([7, 6, 4, 3, 1]))
print(max_profit([2, 4, 1]))
4
0
4
5
0
2
答案 1 :(得分:1)
对于这个问题,最有效的算法是O(N)时间和O(1)空间,它的效率再也无法提高,因为在这里,我们必须至少访问每个元素一次:
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
max_price = 0
min_price = float('inf')
for i in range(len(prices)):
if prices[i] < min_price:
min_price = prices[i]
if prices[i] > max_price:
max_price = max(max_price, prices[i] - min_price)
return max_price
答案 2 :(得分:1)
我不擅长python,但是我可以向您展示如何使用Java。
public int maxProfit(int[] prices) {
int n = prices.length;
if(n==0) return 0;
int[] L = new int[n];
int[] R = new int[n];
L[0]=prices[0];
for(int i=1;i<n;i++){
L[i]=Math.min(L[i-1], prices[i]);
}
R[n-1]=prices[n-1];
for(int i=n-2;i>=0;i--){
R[i]=Math.max(R[i+1], prices[i]);
}
int max=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
max = Math.max(max, R[i]-L[i]);
}
return max;
}
这种方法基本上基于陷阱雨水问题。
答案 3 :(得分:0)
此问题不需要动态编程。您想找到x[i]
的最大值-(最小价格直到i)。因此,要找到卖出时间,您只需进行评估(如果您正在处理numpy
数组)sell = np.argmax(x- np.minumum.accumulate(x))
对于购买时间,您需要`np.argmin(x [:sell])
如果您使用的是香草python(无numpy
),则只需实现累积的minimum
和argmin/argmax
(相当琐碎)即可。