Dare2Solve
The goal is to maximize profit by taking advantage of daily price differences. Since you can buy and sell on the same day, the problem can be reduced to summing up all positive differences between consecutive prices. This approach ensures that you capture all profitable opportunities.
maxProfit
to 0.maxProfit
.maxProfit
.This approach works because it effectively buys on every local minimum and sells on every local maximum, capturing all profitable transactions.
The time complexity is O(n), where n
is the length of the array. This is because we iterate through the array once.
The space complexity is O(1) since we are using only a single additional variable to keep track of the profit.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxProfit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
};
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
maxProfit += prices[i] - prices[i - 1]
return maxProfit
class Solution {
public int maxProfit(int[] prices) {
int price = prices[0];
int maxProfit = 0;
for(int i = 1; i < prices.length; i++) {
if(prices[i] > price ) {
maxProfit += prices[i] - price;
}
price = prices[i];
}
return maxProfit;
}
}
function maxProfit(prices) {
let maxProfit = 0
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1]
}
}
return maxProfit
}