Today's LeetCode challenge taught me a valuable lesson about how tracking state can be more effective than manipulating arrays. The problem seemed straightforward: find the maximum profit you could make by buying and selling a stock once. However, my initial approach revealed I need to really consider the problem- a theme that is revealing itself in this 30 day challenge.
The Challenge
Given an array of stock prices where each price represents a day, find the maximum profit you could make by buying on one day and selling on a future day.
Example:
Input: prices = [7,1,5,3,6,4]
Output: 5
// Buy on day 2 (price = 1) and sell on day 5 (price = 6)
My Initial Approach: Array Manipulation
My first instinct was to split the array and look for patterns:
var maxProfit = function(prices) {
const tempArrayBegin = prices.slice(0, Math.ceil(prices.length/2));
const tempArrayEnd = prices.slice(Math.ceil(-1 * prices.length/2));
const buy = (Math.min(...tempArrayBegin) > Math.min(...tempArrayEnd) ?
Math.min(...tempArrayBegin) : Math.min(...tempArrayEnd));
// ... more logic to find selling price where I looped through the prices array
// to find the profit
};
This core logic passed the initial LeetCode test; but failed in other test. As I looked I at the array inputs, I realized that:
Finding the lowest price doesn't always lead to highest profit
The logic became complex trying to handle edge cases(Yes, the code above is the result of several attempts of trying to pass different test)
Splitting the array didn't guarantee finding the best buy/sell points
The Solution: Track State
Interestingly, something clicked that made me realize I should track two things as we move through the array:
The minimum price we've seen so far
The maximum profit possible up to that point
var maxProfit = function(prices) {
let minPrice = prices[0];
let maxProfit = 0;
for(let i = 1; i < prices.length; i++) {
if(prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
if(prices[i] < minPrice) {
minPrice = prices[i];
}
}
return maxProfit;
};
Key Learnings
State vs Structure: Sometimes tracking state (minPrice, maxProfit) is more effective than manipulating data structure (splitting arrays).
One Pass is Enough: I didn’t need multiple passes through the array - we can make decisions as we go.
Local vs Global: At each step, I’m tracking both local information (current minimum price) and global information (best profit so far).
Think Like the Problem: Instead of trying to find buy and sell days separately, think about how profit is calculated at each possible point.
Impact on Future Problem-Solving
This challenge changed how I'll approach similar problems. Instead of immediately thinking about array manipulation, I'll ask:
What state do I need to track?
What can I calculate at each step?
How can I make one pass through the data efficient?