Compare Sums of Bitonic Parts Problem
Description
LeetCode Problem 3909.
You are given a bitonic array nums of length n.
Split the array into two parts:
- Ascending part: from index 0 to the peak element (inclusive).
- Descending part: from the peak element to index
n - 1(inclusive).
The peak element belongs to both parts.
Return:
- 0 if the sum of the ascending part is greater.
- 1 if the sum of the descending part is greater.
- -1 if both sums are equal.
Notes:
- A bitonic array is an array that is strictly increasing up to a single peak element and then strictly decreasing.
- An array is said to be strictly increasing if each element is strictly greater than its previous one (if exists).
- An array is said to be strictly decreasing if each element is strictly smaller than its previous one (if exists).
Example 1:
Input: nums = [1,3,2,1]
Output: 1
Explanation:
- Peak element is nums[1] = 3
- Ascending part = [1, 3], sum is 1 + 3 = 4
- Descending part = [3, 2, 1], sum is 3 + 2 + 1 = 6
- Since the descending part has a larger sum, return 1.
Example 2:
Input: nums = [2,4,5,2]
Output: 0
Explanation:
- Peak element is nums[2] = 5
- Ascending part = [2, 4, 5], sum is 2 + 4 + 5 = 11
- Descending part = [5, 2], sum is 5 + 2 = 7
- Since the ascending part has a larger sum, return 0.
Example 3:
Input: nums = [1,2,4,3]
Output: -1
Explanation:
- Peak element is nums[2] = 4
- Ascending part = [1, 2, 4], sum is 1 + 2 + 4 = 7
- Descending part = [4, 3], sum is 4 + 3 = 7
- Since both parts have equal sums, return -1.
Constraints:
3 <= n == nums.length <= 10^51 <= nums[i] <= 10^9numsis a bitonic array.
Solution
Approach: Simulation
Let l be the sum of the ascending part (up to and including the peak) and r the sum of the descending part (from the peak to the end). The peak belongs to both parts.
Start with l = nums[0] and r = sum(nums). Walk from the second element while the array is still increasing. At each step add nums[i] to l and remove nums[i - 1] from r, because that element now lies before the part counted in r. Stop at the peak, which is the first element followed by a smaller one.
Then compare l and r: return -1 if they are equal, 0 if l is larger, and 1 otherwise.
Complexity: time O(n), space O(1), where n is the length of the array.
class Solution:
def compareBitonicSums(self, nums: List[int]) -> int:
l, r = nums[0], sum(nums)
for a, b in zip(nums, nums[1:]):
if a > b:
break
l += b
r -= a
if l == r:
return -1
return 0 if l > r else 1