Leetcode 122. Best Time to Buy and Sell Stock II
The problem is to determine the maximum profit that can be achieved from an array where each element represents the price of a stock on a given day. You are allowed to buy and sell the stock multiple times, but you must sell the stock before you buy again.
To solve this problem, we employ a greedy algorithm. The idea is to accumulate profit by capturing all increases across consecutive days. We can achieve this by iterating through the array and summing up all profitable differences (i.e., prices[i+1] - prices[i] if it results in a gain).
#include <vector>
class Solution {
public:
int maxProfit(std::vector<int>& prices) {
int maxProfit = 0;
for (size_t i = 1; i < prices.size(); ++i) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
};
The time complexity for this solution is (O(n)) where (n) is the number of days (or the length of the prices
array). This is because we only iterate through the array once.
maxProfit
of 0.prices
array starting from the second day:
prices[i]
) is greater than the price of the previous day (prices[i-1]
), we add the difference to maxProfit
.maxProfit
at the end of the iteration gives the result.This greedy approach ensures that we capture all profitable transactions without explicitly tracking buy/sell operations but rather focusing directly on profitable increments.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?