334. Increasing Triplet Subsequence

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples: Given [1, 2, 3, 4, 5], return true.

Given [5, 4, 3, 2, 1], return false.

Related issue Longest Increasing Subsequence

Use two variables, min, seondMin to narrow the search range, initially, both set to MAX_VALUE, min is the smallest number so far, and secondMin is a number larger than min, but after min's position.

if val <= min, min =val;
if min < val <= secondMin, secondMin = val;
else return true; val is the third val in the sequence.
public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min = Integer.MAX_VALUE;
        int secondMin = Integer.MAX_VALUE;

        for(int val : nums){
            if(val <= min){
                min = val;
            }else if(min < val && val <= secondMin){
                secondMin = val;
            }else{
                return true;
            }
        }
        return false;
    }
}

results matching ""

    No results matching ""