#3745

Maximize Expression of Three Elements

Easy
ArrayGreedySortingEnumerationGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

To maximize a + b - c, we should select the two largest numbers for a and b, and the smallest number for c. This reduces the problem to finding these three numbers efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the two largest numbers in the array.
  2. 2Step 2: Find the smallest number in the array.
  3. 3Step 3: Calculate the expression using the two largest and the smallest number.
solution.py12 lines
1def maxExpression(nums):
2    largest1 = largest2 = float('-inf')
3    smallest = float('inf')
4    for num in nums:
5        if num > largest1:
6            largest2 = largest1
7            largest1 = num
8        elif num > largest2:
9            largest2 = num
10        if num < smallest:
11            smallest = num
12    return largest1 + largest2 - smallest

Complexity note: We traverse the array once to find the required values, resulting in linear time complexity.

  • 1Select the two largest values for a and b.
  • 2Select the smallest value for c.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.