I'm working on a leet code problem with the following instructions:
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
In my code below, I expect to remove the Max number from the array only if it's in index 0 of the array. When checking the debugger, I see that the entire array is deleted except index 0. Why is splice not working as intended?
var maxProfit = function (prices) {
let theMin = Math.min(...prices)
let minPosition = prices.indexOf(theMin)
let theMax = Math.max(...prices)
let maxPosition = prices.lastIndexOf(theMax)
if (maxPosition === 0) {
prices = prices.splice(0, 1)
if (prices.length === 0) {
return 0
}
maxProfit(prices)
}
return theMax - theMin
};
splice
does not return a modified copy of the array. The array is modified in-place, and what is returned is the deleted subarray, if any.
In effect, your code is:
const deletedElements = prices.splice(0, 1);
prices = deletedElements;
You deleted the first element from the array, then replaced that array with another array which only contains the first element. Thus, it is not that only the first element is returned, as you claim. splice
is working exactly as documented.
Also, prices.splice(0, 1)
is more legibly written as prices.shift()
.