C#: Easy to Understand Solution with Explanation. (Accepted)


  • 0

    0_1523506241224_da98b6f7-65a1-4424-97ca-92a5d24f45b2-image.png

    Basic Idea:
    Keep 2 values when checking all elements in the array

    • first value: Minimum until now.
    • second value from the first value’s position until now. i.e. SecondMinimum (second > first)

    Now, if we can find a third value, that is larger than first and second values at the same time, there must exist a triplet sub-sequence i.e return true.

    public class Solution {
        public bool IncreasingTriplet(int[] nums) {
            int first = int.MaxValue;
            int second = int.MaxValue;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] <= first)
                    first = nums[i];
                else if (nums[i] <= second)
                    second = nums[i];
                else
                    return true;                
            }
            return false;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.