Maximize Expression of Three Elements Problem
#3745
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3745.
You are given an integer array nums.
Choose three elements a, b, and c from nums at distinct indices such that the value of the expression a + b - c is maximized.
Return an integer denoting the maximum possible value of this expression.
Example 1:
Input: nums = [1,4,2,5]
Output: 8
Explanation:
We can choose a = 4, b = 5, and c = 1. The expression value is 4 + 5 - 1 = 8, which is the maximum possible.
Example 2:
Input: nums = [-2,0,5,-2,4]
Output: 11
Explanation:
We can choose a = 5, b = 4, and c = -2. The expression value is 5 + 4 - (-2) = 11, which is the maximum possible.
Constraints:
3 <= nums.length <= 100-100 <= nums[i] <= 100
Solution
Approach: Two largest and the smallest
To maximize a + b - c, take a and b as the two largest values and c as the smallest. Since the array has at least three elements, the three picks are always at distinct indices (the smallest is never one of the two largest unless values tie, and equal values at different indices are fine).
One pass tracks the largest, the second largest and the smallest value, and the answer is largest + second - smallest.
Complexity: time O(n), space O(1).
from math import inf
class Solution:
def maximizeExpressionOfThree(self, nums: List[int]) -> int:
a = b = -inf
c = inf
for x in nums:
if x < c:
c = x
if x >= a:
a, b = x, a
elif x > b:
b = x
return a + b - c