Leetcode 553. Optimal Division
Leetcode Problem 553: Optimal Division
You are given an integer array nums
. The optimal division of this array is the expression that results in the largest possible value after performing division operations between its elements. Specifically, we need to find a way to parenthesize the array such that the resulting expression has the maximum value.
For example, for the array [1000, 100, 10, 2]
, the optimal division is:
( \frac{1000}{(100 / (10 / 2))} )
The goal is to return this expression as a string.
Input: nums = [1000, 100, 10, 2]
Output: "1000/(100/10/2)"
nums
array?
nums
?
The problem is essentially about where to place the parentheses to maximize the division result.
When you have more than two numbers in the division sequence, the maximum value is always obtained by dividing the first number by the result of dividing the rest of the numbers in sequence.
For example, given numbers [a, b, c, d]
, the optimal division is:
[
a / \frac{b}{\frac{c}{d}}
]
which can be represented as a/(b/c/d)
.
nums
has only one element, return that element as a string.nums
has only two elements, return a/b
.import java.util.Arrays;
public class OptimalDivision {
public String optimalDivision(int[] nums) {
int n = nums.length;
// Handle case with only one number.
if (n == 1) return Integer.toString(nums[0]);
// Handle case with only two numbers.
if (n == 2) return nums[0] + "/" + nums[1];
// Handle case with more than two numbers.
// Form the string for optimal division.
StringBuilder sb = new StringBuilder();
sb.append(nums[0]).append("/(").append(nums[1]);
for (int i = 2; i < n; i++) {
sb.append("/").append(nums[i]);
}
sb.append(")");
return sb.toString();
}
// Example usage:
public static void main(String[] args) {
OptimalDivision solution = new OptimalDivision();
int[] nums = {1000, 100, 10, 2};
System.out.println(solution.optimalDivision(nums)); // Output: "1000/(100/10/2)"
}
}
The time complexity of the solution is O(n), where n is the number of elements in the array nums
. This is because we are iterating through the array once to construct the result string.
The space complexity is also O(n) due to the construction of the result string which potentially holds up to 2n characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?