Skip to content

Instantly share code, notes, and snippets.

@gauravat16
Created November 25, 2018 07:30
Show Gist options
  • Save gauravat16/739626545d9878a753266e3af406e5fe to your computer and use it in GitHub Desktop.
Save gauravat16/739626545d9878a753266e3af406e5fe to your computer and use it in GitHub Desktop.
Get a triplet i, j, k. i<j<k & arr[i]<arr[j]<arr[k]
/*
* Copyright (c) 2018. Gaurav Sharma, All rights reserved.
*/
package practice;
public class SortedTriplet {
private static boolean hasTriplet(int[] arr) {
/**
* We need 3 indices i, j, k. i<j<k &
*
* arr[i]<arr[j]<arr[k]
*
* Keep minVal (i) and maxVal(k) in track.
*/
int minVal = Integer.MAX_VALUE, maxVal = Integer.MAX_VALUE;
/**
* Loop over the array.
*/
for (int currVal : arr) {
/**
* If current val is <= to minVal, update minVal.
* If current val is <= to maxVal, update maxVal.
*
* If currVal is <= minVal && currVal >= maxVal && maxVal != Integer.MAX_VALUE && minVal != Integer.MAX_VALUE
* then we have found the max value. return true at that point.
*/
if (currVal <= minVal) {
minVal = currVal;
} else if (currVal <= maxVal) {
maxVal = currVal;
} else if (maxVal != Integer.MAX_VALUE && minVal != Integer.MAX_VALUE) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(hasTriplet(new int[]{5, 4, 3, 2, 1}));
System.out.println(hasTriplet(new int[]{1, 2, 3, 4, 5}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment