Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created November 20, 2016 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/3fce12eff5838fa10bff0792547d0779 to your computer and use it in GitHub Desktop.
Save jianminchen/3fce12eff5838fa10bff0792547d0779 to your computer and use it in GitHub Desktop.
Minimum Cost - TreeSet - Java code study - HackerRAnk woman codesprint #2 -
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numYears = sc.nextInt();
long[] data = new long[numYears];
for (int i = 0; i < numYears; i++) {
data[i] = sc.nextLong();
}
TreeSet<Long> values = new TreeSet<>();
long best = Long.MAX_VALUE;
for (int i = numYears-1; i >= 0; i--) {
Long smaller = values.floor(data[i]);
if (smaller != null) {
long diff = (data[i] - smaller);
if (diff >= 0) {
best = Math.min(best, diff);
}
}
values.add(data[i]);
}
System.out.println(best);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment