Last updated on October 5th, 2024 at 04:55 pm
Here, We see Increasing Triplet Subsequence LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Array
Companies
Level of Question
Medium
Increasing Triplet Subsequence LeetCode Solution
Table of Contents
Problem Statement
Given an integer array nums
, return true
if there exists a triple of indices (i, j, k)
such that i < j < k
and nums[i] < nums[j] < nums[k]
. If no such indices exists, return false
.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
1. Increasing Triplet Subsequence LeetCode Solution C++
class Solution { public: bool increasingTriplet(vector<int>& nums) { int n=nums.size(); if(n<3)return false; int low=INT_MAX, mid=INT_MAX; for(int i=0;i<n;i++) { if(nums[i]>mid) return true; else if(nums[i]<low) low=nums[i]; else if(nums[i]> low and nums[i]<mid) mid=nums[i]; } return false; } };
2. Increasing Triplet Subsequence LeetCode Solution Java
class Solution { public boolean increasingTriplet(int[] nums) { int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE; for(int num : nums){ if(num <= min) min = num; else if(num < secondMin) secondMin = num; else if(num > secondMin) return true; } return false; } }
3. Increasing Triplet Subsequence Solution JavaScript
var increasingTriplet = function(nums) { let firstNumber = Infinity; let secondNumber = Infinity; for (let currentNumber of nums) { if (currentNumber > secondNumber && currentNumber > firstNumber) { return true; } if (currentNumber > firstNumber) { secondNumber = currentNumber; } else { firstNumber = currentNumber; } } return false; };
4. Increasing Triplet Subsequence Solution Python
class Solution(object): def increasingTriplet(self, nums): first = second = float('inf') for n in nums: if n <= first: first = n elif n <= second: second = n else: return True return False