Given an integer array nums, return trueif there exists a triple of indices(i, j, k)such thati < j < kandnums[i] < nums[j] < nums[k]. If no such indices exists, return false.
OR
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
This problem can be transformed into checking if there’s a sequence where the_smallest_so_far < the_second_smallest_so_far < current. We use x, y, and z to represent these three numbers, respectively.
Here is the approach:
Initialize Variables:
Use first_min to keep track of the smallest element so far.
Use second_min to keep track of the second smallest element so far.
Use potential_min to store a new minimum which might be the start of a new sequence.
Iterate Through the Array:
If nums[i] is less than first_min, update first_min.
If nums[i] is greater than first_min but less than second_min, update second_min.
If nums[i] is greater than both first_min and second_min, return true.
Handle any new potential minimums and adjust the series accordingly.
publicclassSolution {
publicbooleanincreasingTriplet(int[] nums) {
if (nums.length< 3) {
returnfalse;
}
int firstMin = Integer.MAX_VALUE;
int secondMin = Integer.MAX_VALUE;
for (int num : nums) {
if (num <= firstMin) {
firstMin = num; // Update firstMin if num is smaller } elseif (num <= secondMin) {
secondMin = num; // Update secondMin if num is larger than firstMin but smaller than secondMin } else {
returntrue; // Found third number, return true }
}
returnfalse; // No such triplet found }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defincreasingTriplet(self, nums: List[int]) -> bool:
if len(nums) <3:
returnFalse first_min = float('inf')
second_min = float('inf')
for num in nums:
if num <= first_min:
first_min = num # Update first_min if num is smallerelif num <= second_min:
second_min = num # Update second_min if num is larger than first_min but smaller than second_minelse:
returnTrue# Found third number, return truereturnFalse# No such triplet found