2.5 KiB
Leetcode Increasing-Triplet-Subsequence
2022-09-04 14:23
Algorithms:
#algorithm #greedy
Data structures:
#DS #array
Difficulty:
#coding_problem #difficulty-medium
Additional tags:
#leetcode #CS_list_need_understanding
Revisions:
N/A
Links:
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
.
Examples
Example 1:
Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Constraints
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
Thoughts
[!summary] This is a #greedy problem.
Use two variables: small
and big
to keep track of stuff.
For each element, there are three possibilities:
- the element is smaller than
small
, assign the element tosmall
small
andbig
doesn't representi
andj
, accurately, they get updated lazily. And because we don't need to showi
,j
,k
, this will be just fine
- the element is greater than
small
:- the element is smaller than
big
, changebig
, this allows more possibilities - the element is bigger than
big
, found, exit loop.
- the element is smaller than
Why not #stack ?
Similar to Leetcode Next-Greater-Element-I, the property of stack can be used for continuity related problem, but here we don't need this.
Solution
class Solution {
public:
bool increasingTriplet(vector<int> &nums) {
// greedy algorithm
int small = INT_MAX, big = INT_MAX;
for (int i = 0, size = nums.size(); i < size; i++) {
if (nums[i] <= small) {
// Use equal sign here, to avoid small and big being same.
small = nums[i];
} else if (nums[i] <= big) {
// Use equal sign here, to avoid three consecutive
// same numbers
big = nums[i];
} else {
return true;
}
}
return false;
}
};