LeetCode 2921: Maximum Profitable Triplets With Increasing Prices II
Problem Description
Explanation:
To solve this problem, we can iterate through the given prices array and keep track of the maximum profit that can be obtained by considering three elements (triplets) in increasing order. We maintain three variables to store the maximum profit that can be obtained by considering each triplet ending at the current index.
- Initialize three variables
first
,second
, andthird
to store the maximum profit for the first, second, and third element of the triplet ending at the current index. - Iterate through the prices array and update these variables based on the current price.
- At each index
i
, we update thefirst
,second
, andthird
values as follows:first = max(first, -price[i])
(max profit if the first element is at indexi
)second = max(second, first + price[i])
(max profit if the second element is at indexi
)third = max(third, second - price[i])
(max profit if the third element is at indexi
)
- After iterating through the prices array, the maximum profit will be stored in the
third
variable.
Time Complexity: O(N), where N is the number of elements in the prices array. Space Complexity: O(1)
:
Solutions
class Solution {
public int maxProfit(int[] prices) {
int first = Integer.MIN_VALUE, second = 0, third = 0;
for (int price : prices) {
first = Math.max(first, -price);
second = Math.max(second, first + price);
third = Math.max(third, second - price);
}
return third;
}
}
Loading editor...