LeetCode 2907: Maximum Profitable Triplets With Increasing Prices I

LeetCode 2907 Solution 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. :

LeetCode 2907 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 2907

Improve Your LeetCode 2907 Solution

Use the editor below to refine the provided solution for LeetCode 2907. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems