Original link: leetcode-cn.com/problems/be…
Answer:
- When you encounter the price of day I, you just need to consider the profit generated by trading with all subsequent prices and take the maximum.
- You can use a two-level loop, with the first level enumerating the prices of day I and the second level enumerating the prices after that and calculating.
/ * * *@param {number[]} prices
* @return {number}* /
var maxProfit = function (prices) {
let max = 0; // Store maximum profits
// The first pass assumes that the stock has been bought at the ith price
for (let i = 0; i < prices.length - 1; i++) {
// Enumerate all prices after I for the second time
for (let j = i + 1; j < prices.length; j++) {
// Calculate the current profit and compare it with the maximum value stored, whichever is greater
max = Math.max(prices[j] - prices[i], max); }}return max;
};
Copy the code