Problem
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.
Algorithm
Dynamic Programming (DP). Following the increasing length of tuples, scan the array from front to back each time, saving the position of the smallest prefix of length L-1: if the data is larger than the smallest prefix, a new sequence of length L is found, otherwise update the prefix.
Code
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
nLen = len(nums)
dp = [1] * nLen
for i in range(1, 3):
min_value_index = 0
while min_value_index < nLen and dp[min_value_index] < i:
min_value_index += 1
if min_value_index >= nLen:
return False
j = min_value_index+1
while j < nLen:
if dp[j] == i:
if nums[min_value_index] < nums[j]:
dp[j] = i+1
else:
min_value_index = j
j += 1
return max(dp) >= 3