#3745
Easy Algorithms Maximize expression of three elements
Array Greedy Sorting Enumeration
72.4% acceptance
Jan 13, 2026
52
1
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn maximize_expression_of_three(nums: Vec<i32>) -> i32 {
let mut sorted = nums.clone();
sorted.sort_unstable();
let n = sorted.len();
// max a+b-c: pick two largest as a,b and smallest as c
// but they must be distinct indices, not distinct values
// Use top 2 max + bottom 1 min from original array
// Sort descending: top two + negate minimum
sorted[n-1] + sorted[n-2] - sorted[0]
}
}