#553
Medium Algorithms Optimal division
Array Math Dynamic Programming
62.8% acceptance
Jan 13, 2026
419
1636
You are given an integer array nums. The adjacent integers in nums will perform the float division.
For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.
Return the corresponding expression that has the maximum value in string format.
Note: your expression should not contain redundant parenthesis.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn optimal_division(nums: Vec<i32>) -> String {
let n = nums.len();
if n == 1 {
return nums[0].to_string();
}
if n == 2 {
return format!("{}/{}", nums[0], nums[1]);
}
// For 3+ numbers: a[0]/(a[1]/a[2]/.../a[n-1]) is always maximum
let inner = nums[1..].iter().map(|x| x.to_string()).collect::<Vec<_>>().join("/");
format!("{}/({})" , nums[0], inner)
}
}