Let's look at an example array: 1, 2, -1, 1, -2, 3. When we go through the first two element, we are all good. Then, we encounter -1, here we face a decision, should we update the current minimum to -1?
Let's see why we should and why we shouldn't. -1 is a safer move than 1, what if later our solution is -1, 0, 1? Then we definitely want to update it. However, you might say, if we update it to -1, then 2 shouldn't be in our solution anymore, according to the "subsequence" rule.
Well, the answer is YES, but we only update the minimum, keeping the second minimum (which is 2 here).The argument is as following: when we keep the second minimum (call it min2), this means that we only count increasing when the next value is greater than min2. You see, by changing min1 to a smaller value, it doesn't really affect the decision we are going to make about adding an increasing element. However, if we see the next value is smaller than min2 but greater than min1, we then want to update min2.
In this way, we always keep track the safest possible value yet maintain the order we have for now.
In actual implementation, I used a stack instead of min1, min2. It turned out to be much easier to handle. Well, who knows such a seeming simple question took me good two hours to think through - this kind of question is very tricky.
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
return
Given
[1, 2, 3, 4, 5],return
true.
Given
return
[5, 4, 3, 2, 1],return
false.class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) < 3: return False counter = 1 stack = [] for i in nums: if len(stack) == 0: stack.append(i) elif i < stack[0]: stack[0] = i elif len(stack) == 1 and i > stack[0]: stack.append(i) elif len(stack) == 2 and stack[0] < i < stack[1]: stack[1] = i elif len(stack) == 2 and i > stack[1]: return True return False
