LeetCode 2921: Maximum Profitable Triplets With Increasing Prices II Solution
Master LeetCode problem 2921 (Maximum Profitable Triplets With Increasing Prices II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2921. Maximum Profitable Triplets With Increasing Prices II
Problem Explanation
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, andthirdto 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, andthirdvalues 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
thirdvariable.
Time Complexity: O(N), where N is the number of elements in the prices array. Space Complexity: O(1)
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2921 (Maximum Profitable Triplets With Increasing Prices II)?
This page provides optimized solutions for LeetCode problem 2921 (Maximum Profitable Triplets With Increasing Prices II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2921 (Maximum Profitable Triplets With Increasing Prices II)?
The time complexity for LeetCode 2921 (Maximum Profitable Triplets With Increasing Prices II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2921 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2921 in Java, C++, or Python.