# Leetcode Increasing-Triplet-Subsequence

2022-09-04 14:23

> ##### Algorithms:
>
> #algorithm #greedy
>
> ##### Data structures:
>
> #DS #array
>
> ##### Difficulty:
>
> #coding_problems #difficulty_medium
>
> ##### Additional tags:
>
> #leetcode #CS_list_need_understanding
>
> ##### Revisions:
>
> 2022-09-21

##### Links:

- [Link to problem](https://leetcode.com/problems/increasing-triplet-subsequence/)
- [Solution with explanation](https://leetcode.com/problems/increasing-triplet-subsequence/discuss/78993/Clean-and-short-with-comments-C%2B%2B)

  ***

### 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
  to `small`

  > `small` and `big` doesn't represent `i` and `j`,
  > accurately, they get updated lazily.
  > And because we don't need to show `i`, `j`, `k`, this
  > will be just fine

- the element is greater than `small`:

  - the element is smaller than `big`, change `big`, this
    allows more possibilities
  - the element is bigger than `big`, found, exit loop.

    > #### 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

```cpp
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;
}
};
```
