Skip to content

Commit 3de29fb

Browse files
Increasing Triplet Subsequence : Accepted
1 parent 993ac52 commit 3de29fb

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ My accepted leetcode solutions to some of the common interview problems.
2828
- [Maximum Swap](problems/src/array/MaximumSwap.java) (Medium)
2929
- [H-Index](problems/src/array/HIndex.java) (Medium)
3030
- [Insert Interval](problems/src/array/InsertInterval.java) (Hard)
31+
- [Increasing Triplet Subsequence](problems/src/array/IncreasingTripletSubsequence.java) (Medium)
3132

3233
#### [Backtracking](problems/src/backtracking)
3334

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package array;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 17/12/2017.
7+
* Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
8+
9+
Formally the function should:
10+
Return true if there exists i, j, k
11+
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
12+
Your algorithm should run in O(n) time complexity and O(1) space complexity.
13+
14+
Examples:
15+
Given [1, 2, 3, 4, 5],
16+
return true.
17+
18+
Given [5, 4, 3, 2, 1],
19+
return false.
20+
*/
21+
public class IncreasingTripletSubsequence {
22+
23+
/**
24+
* Main method
25+
* @param args
26+
* @throws Exception
27+
*/
28+
public static void main(String[] args) throws Exception{
29+
int[] A = {1, 2, 3, 4, 5};
30+
System.out.println(new IncreasingTripletSubsequence().increasingTriplet(A));
31+
}
32+
33+
public boolean increasingTriplet(int[] nums) {
34+
int[] A = new int[3];
35+
Arrays.fill(A, Integer.MAX_VALUE);
36+
for (int num : nums) {
37+
if (num < A[0]) {
38+
A[0] = num;
39+
} else if (num < A[1] && num > A[0]) {
40+
A[1] = num;
41+
} else if (num < A[2] && num > A[1]) {
42+
return true;
43+
}
44+
}
45+
return false;
46+
}
47+
}
48+

0 commit comments

Comments
 (0)