Trionic Array II Problem
Description
LeetCode Problem 3640.
You are given an integer array nums of length n.
A trionic subarray is a contiguous subarray nums[l...r] (with 0 <= l < r < n) for which there exist indices l < p < q < r such that:
nums[l...p]is strictly increasing,nums[p...q]is strictly decreasing,nums[q...r]is strictly increasing.
Return the maximum sum of any trionic subarray in nums.
Example 1:
Input: nums = [0,-2,-1,-3,0,2,-1]
Output: -4
Explanation:
Pick l = 1, p = 2, q = 3, r = 5:
- nums[l...p] = nums[1...2] = [-2, -1] is strictly increasing (-2 < -1).
- nums[p...q] = nums[2...3] = [-1, -3] is strictly decreasing (-1 > -3)
- nums[q...r] = nums[3...5] = [-3, 0, 2] is strictly increasing (-3 < 0 < 2).
- Sum = (-2) + (-1) + (-3) + 0 + 2 = -4.
Example 2:
Input: nums = [1,4,2,7]
Output: 14
Explanation:
Pick l = 0, p = 1, q = 2, r = 3:
- nums[l...p] = nums[0...1] = [1, 4] is strictly increasing (1 < 4).
- nums[p...q] = nums[1...2] = [4, 2] is strictly decreasing (4 > 2).
- nums[q...r] = nums[2...3] = [2, 7] is strictly increasing (2 < 7).
- Sum = 1 + 4 + 2 + 7 = 14.
Constraints:
4 <= n = nums.length <= 10^5-10^9 <= nums[i] <= 10^9- It is guaranteed that at least one trionic subarray exists.
Solution
Approach: Grouped Loop
Scan the array once and find each increasing, decreasing, increasing pattern.
From a starting index l, move right while the values strictly increase; if this part has a single element, skip ahead. Let p be the last index of the increase. Then move right while the values strictly decrease; if that part is empty, the array ends, or the next value is equal, there is no trionic subarray here. Let q be the last index of the decrease.
The best subarray for this pattern consists of:
- the elements
nums[p - 1]tonums[q + 1], which are mandatory (the last two of the first rise, the whole fall, and the first step of the final rise); - the best extension to the right of
q + 1along the final increase (the largest prefix sum of that run, possibly empty); - the best extension to the left of
p - 1along the first increase (the largest suffix sum of that run, possibly empty).
Update the answer, then continue from q, since the last increasing run can start the next pattern.
Complexity: O(n) time and O(1) space, where n is the length of the array.
from math import inf
class Solution:
def maxSumTrionic(self, nums: List[int]) -> int:
n = len(nums)
i = 0
ans = -inf
while i < n:
l = i
i += 1
while i < n and nums[i - 1] < nums[i]:
i += 1
if i == l + 1:
continue
p = i - 1
s = nums[p - 1] + nums[p]
while i < n and nums[i - 1] > nums[i]:
s += nums[i]
i += 1
if i == p + 1 or i == n or nums[i - 1] == nums[i]:
continue
q = i - 1
s += nums[i]
i += 1
mx = t = 0
while i < n and nums[i - 1] < nums[i]:
t += nums[i]
i += 1
mx = max(mx, t)
s += mx
mx = t = 0
for j in range(p - 2, l - 1, -1):
t += nums[j]
mx = max(mx, t)
s += mx
ans = max(ans, s)
i = q
return ans