Description
You are given an integer array nums of length n.
An array is trionic if there exist indices 0 < p < q < n − 1 such that:
nums[0...p]is strictly increasing,nums[p...q]is strictly decreasing,nums[q...n − 1]is strictly increasing.
Return true if nums is trionic, otherwise return false.
Example 1:
Input: nums = [1,3,5,4,2,6]
Output: true
Explanation:
Pick p = 2, q = 4:
nums[0...2] = [1, 3, 5]is strictly increasing (1 < 3 < 5).nums[2...4] = [5, 4, 2]is strictly decreasing (5 > 4 > 2).nums[4...5] = [2, 6]is strictly increasing (2 < 6).
Example 2:
Input: nums = [2,1,3]
Output: false
Explanation:
There is no way to pick p and q to form the required three segments.
Constraints:
3 <= n <= 100-1000 <= nums[i] <= 1000
Solutions
The function checks whether an array of numbers follows a trionic pattern — a sequence that increases, then decreases, then increases again. It uses three boolean flags (increased, decreased, finished) to track which phases of this pattern have been completed. Starting from the second element, it iterates through the array comparing each number to the previous one; if the numbers increase and the decrease phase hasn't started, it marks increased as true; if they decrease after increasing, it marks decreased as true; if they increase again after decreasing, it marks finished as true. If at any point the comparison doesn't match the expected pattern (e.g., decreasing before increasing, or skipping ahead), it immediately returns false. The function returns true only if it successfully completes all three phases and reaches the end of the array with finished set to true.
/**
* @param {number[]} nums
* @return {boolean}
*/
var isTrionic = function(nums) {
let increased = false;
let decreased = false;
let finished = false;
for (let i = 1; i < nums.length; i++) {
if (!decreased && !finished && nums[i] > nums[i - 1]) {
if (!increased) increased = true;
} else if (increased && !finished && nums[i] < nums[i - 1]) {
if (!decreased) decreased = true;
} else if (increased && decreased && nums[i] > nums[i - 1]) {
if (!finished) finished = true;
} else {
return false;
}
}
return finished;
};