[LeetCode][334. Increasing Triplet Subsequence] Why Greedy Works?
By Long Luo
This article is the solution Why Greedy Works? of Problem 334. Increasing Triplet Subsequence.
Intution
We can easily find that whether there exists a triple of indices \((i, j, k)\) such that \(i < j < k\) and \(nums[i] < \textit{nums}[j] < \textit{nums}[k]\) only traversing the array once, but the problem is how to make our mind into algorithms.
Brute Force
It’s easy to use Brute Force way to solve this problem, but the time complexity is \(O(n^3)\), it will TLE, so we need to find a better way.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public static boolean increasingTriplet(int[] nums) {
if (nums == null || nums.length < 3) {
return false;
}
int len = nums.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
for (int k = j + 1; k < len; k++) {
if (nums[i] < nums[j] && nums[j] < nums[k]) {
return true;
}
}
}
}
return false;
}
Analysis
- Time Complexity: \(O(n^3)\)
- Space Complexity: \(O(1)\)
Dynamic Programming
We can also use DP method to solve it.
Let \(dp[i]\) represents the maximum length of a increasing sequence.
\[ dp[i] = \begin{cases} 1 & dp[i] \le dp[j], 0 < j < i \\ dp[j] + 1 & dp[i] > dp[j], 0 < j < i \end{cases} \]