Stock Buy and Sell – Multiple Transaction Allowed
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Maximum profit with unlimited transactions. Sum all positive differences.
Algorithm
- 1For each day: if prices[i] > prices[i-1]: profit += prices[i] - prices[i-1].
Common Pitfalls
- •Same as LC 122. Greedy: capture every upward move. O(n) O(1).
Stock Buy and Sell – Multiple Transaction Allowed.java
Java
// Approach: Greedy. Sum all positive consecutive differences (buy every valley, sell every peak).
// Time: O(n) Space: O(1)
class Solution {
public int maximumProfit(int prices[]) {
int res = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
int diff = prices[i] - prices[i - 1];
res += diff;
}
}
return res;
}
}Advertisement
Was this solution helpful?