0121. Best Time to Buy and Sell Stock (E)
作者:互联网
Best Time to Buy and Sell Stock (E)
题目
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 (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。
代码实现
Java
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;
}
}
JavaScript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let leftMin = prices[0]
let maxProfit = 0
for (let i = 1; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, prices[i] - leftMin)
leftMin = Math.min(leftMin, prices[i])
}
return maxProfit
}
标签:Sell,Buy,return,0121,int,price,maxProfit,prices,leftMin 来源: https://www.cnblogs.com/mapoos/p/13692233.html