Leetcode 553. Optimal Division
You are given an integer array nums
. The adjacent integers in nums
will perform division operations following the order of appearance. For example, given the array nums = [1000, 100, 10, 2]
, we have to find the optimal way to parenthesize the division to get the maximum result.
Return a string that describes the sequence of division operations that will yield the maximum result.
nums
contain negative integers?
nums
will contain only positive integers.nums
?
nums
will be at least 1.nums
has only one element?
To maximize the result of the division, we need to minimize the denominator part by dividing the largest numerator by the smallest possible denominator. This means that we should divide the first number by the result of all subsequent numbers divided together.
Given nums = [a1, a2, ..., an]
:
The optimal division can be represented as:
a1 / (a2 / a3 / ... / an)
If the length of nums
is 1, return a1
directly.
If the length of nums
is 2, return the result in the form of a1 / a2
.
For any n > 2
, return in the form of a1 / (a2 / a3 / ... / an)
.
#include <vector>
#include <string>
std::string optimalDivision(std::vector<int>& nums) {
int n = nums.size();
if (n == 1) {
return std::to_string(nums[0]);
}
if (n == 2) {
return std::to_string(nums[0]) + "/" + std::to_string(nums[1]);
}
std::string result = std::to_string(nums[0]) + "/(" + std::to_string(nums[1]);
for (int i = 2; i < n; ++i) {
result += "/" + std::to_string(nums[i]);
}
result += ")";
return result;
}
The time complexity of this 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, which takes linear time.
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?