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.
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.
低点买入,高点卖出。
由于题目对于交易次数有限制,只能交易(购买、卖出)一次,因此问题的本质就是求波峰浪谷的差值的最大值。
//java
class Solution{
public static int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int min=prices[0];
int result=0;
for(int i=1; i<prices.length; i++) {
result=Math.max(result, Math.max(prices[i]-min, 0));
min=Math.min(min, prices[i]);
}
return result;
}
}
股票买卖最大利润算法
本文介绍了一种算法,用于计算给定股票价格序列中能够获得的最大利润,限制为仅进行一次买卖操作。通过寻找波峰浪谷之间的最大差值,即最高卖价与最低买价之差,来确定最佳买卖时机。

被折叠的 条评论
为什么被折叠?



