Best Time to Buy and Sell Stock (E)
Say you have an array for which the ithi^{th}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.
题意
找到数组中两个数的最大差,注意较小数需要排在较大数之前。
思路
使用类似动态规划的方法:从左向右遍历数组,记录leftMin为以当前下标为右边界的左子数组中的最小值,每次判断更新leftMin,并判断当前值减去leftMin是否大于最大利润,是则更新最大利润。与动态规划的区别在于不需要另开数组记录每一个下标对应的leftMin。
代码实现
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) {
return 0;
}
int leftMin = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < leftMin) {
leftMin = prices[i];
} else if (prices[i] - leftMin > maxProfit) {
maxProfit = prices[i] - leftMin;
}
}
return maxProfit;
}
}
本文介绍了一个算法,用于解决股票交易中的最佳买卖时机问题。通过一次遍历数组,记录历史最低价格和最大利润,实现了O(n)的时间复杂度。适用于只允许进行一次交易的情况。
227

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



