//using 2 arrays prefix suffix sums
/* class IncreasingTripletOptimized {
public static boolean increasingTriplet(int[] b) {
int n = b.length;
if (n < 3) return false;
int[] p = new int[n];
int[] s = new int[n];
// Prefix minimum
p[0] = b[0];
for (int i = 1; i < n; i++) {
p[i] = Math.min(p[i - 1], b[i]);
}
// Suffix maximum
s[n - 1] = b[n - 1];
for (int i = n - 2; i >= 0; i--) {
s[i] = Math.max(s[i + 1], b[i]);
}
// Check condition
for (int i = 1; i <= n - 2; i++) {
if (p[i - 1] < b[i] && b[i] < s[i + 1]) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] a1 = {18, 5, 4, 3, 2, 1, 8, 10};
int[] a2 = {5, 4, 3, 2, 1, 8};
System.out.println(increasingTriplet(a1)); // true
System.out.println(increasingTriplet(a2)); // false
}
}
/*
//i thought it looked like stock span so below stack approach
/*
import java.util.Stack;
public class IncreasingTripletStack {
public static boolean increasingTriplet(int[] arr) {
int n = arr.length;
if (n < 3) return false;
int[] leftMin = new int[n];
int[] rightGreater = new int[n];
// Step 1: Left smaller
leftMin[0] = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
leftMin[i] = Math.min(leftMin[i - 1], arr[i - 1]);
}
// Step 2: Right greater using stack (stock-span style)
Stack<Integer> st = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && st.peek() <= arr[i]) {
st.pop();
}
rightGreater[i] = st.isEmpty() ? Integer.MIN_VALUE : st.peek();
st.push(arr[i]);
}
// Step 3: Check triplet
for (int i = 0; i < n; i++) {
if (leftMin[i] < arr[i] && arr[i] < rightGreater[i]) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] a1 = {18, 5, 4, 3, 2, 1, 8, 10};
int[] a2 = {5, 4, 3, 2, 1, 8};
System.out.println(increasingTriplet(a1)); // true
System.out.println(increasingTriplet(a2)); // false
}
}
*/
class IncreasingSubsequence {
public static boolean increasingTriplet(int[] nums) {
// Initialize the first and second minimums
// wrong logic The variable c is incremented every time a number greater than min1 is found,
// but this does not necessarily indicate that an increasing triplet is being formed. I
/*int c=0;
for (int num : nums) {
if (num < min1) { // assume no same nums
min1 = num;
} else {
c++; // means we found a greater element than min1
if (c==3) return true; // Found an increasing triplet
}
}
*/
for (int num : nums) {
if (num <= min1) {
min1 = num; // Update min1
} else if (num <= min2) {
min2 = num; // Update min2
} else {
// Found a number greater than both min1 and min2
return true; // Found an increasing triplet
}
}
return false; // No increasing triplet found
}
public static void main
(String[] args
) { int[] array1 = {18, 2,5, 7, 3, 4};
int[] array2 = {5, 4, 3, 2, 1, 8};
System.
out.
println(increasingTriplet
(array1
)); // Output: true System.
out.
println(increasingTriplet
(array2
)); // Output: true }
}