LeetCode 2907: Maximum Profitable Triplets With Increasing Prices I Solution
Master LeetCode problem 2907 (Maximum Profitable Triplets With Increasing Prices I), a medium 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.
2907. Maximum Profitable Triplets With Increasing Prices I
Problem Explanation
Explanation:
This problem asks us to find the maximum profit that can be obtained by selecting three numbers (a, b, c) from an array, where a < b < c. The profit is calculated as c - a. We need to return the maximum profit, or 0 if it is not possible to find three numbers satisfying the condition.
To solve this problem, we can iterate through the array and keep track of the minimum value for the first element (a), the maximum profit so far, and the potential third element (c). We update these values as we iterate through the array. If at any point we find a number greater than the potential third element (c), we update the potential third element and recalculate the profit. :
Solution Code
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n < 3) {
return 0;
}
int minFirst = prices[0];
int maxProfit = 0;
int potentialThird = Integer.MIN_VALUE;
for (int i = 1; i < n; i++) {
if (prices[i] > potentialThird) {
maxProfit = Math.max(maxProfit, prices[i] - minFirst);
potentialThird = prices[i];
} else {
minFirst = Math.min(minFirst, prices[i]);
}
}
return maxProfit;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2907 (Maximum Profitable Triplets With Increasing Prices I)?
This page provides optimized solutions for LeetCode problem 2907 (Maximum Profitable Triplets With Increasing Prices I) 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 2907 (Maximum Profitable Triplets With Increasing Prices I)?
The time complexity for LeetCode 2907 (Maximum Profitable Triplets With Increasing Prices I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2907 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2907 in Java, C++, or Python.