LeetCode 553: Optimal Division

Problem Description

Explanation:

To maximize the value of the expression, we need to ensure that the numerator is as large as possible and the denominator is as small as possible. To achieve this, we can always place parentheses around the numbers starting from the second number.

For example, for the input [a, b, c, d], the expression will be a / b / c / d. To maximize the value, we can rewrite this expression as a / (b / c / d). This will ensure the numerator 'a' is as large as possible and the denominator 'b / c / d' is as small as possible.

Algorithm:

  1. If there are only two numbers in the input, return them as they are.
  2. For more than two numbers, return the first number divided by the rest of the numbers in a single group.

Time Complexity: O(n) Space Complexity: O(1)

:

Solutions

class Solution {
    public String optimalDivision(int[] nums) {
        if (nums.length == 1) {
            return String.valueOf(nums[0]);
        }
        if (nums.length == 2) {
            return nums[0] + "/" + nums[1];
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append(nums[0]).append("/(").append(nums[1]);
        for (int i = 2; i < nums.length; i++) {
            sb.append("/").append(nums[i]);
        }
        sb.append(")");
        
        return sb.toString();
    }
}

Loading editor...