Created
November 20, 2016 23:45
-
-
Save jianminchen/3fce12eff5838fa10bff0792547d0779 to your computer and use it in GitHub Desktop.
Minimum Cost - TreeSet - Java code study - HackerRAnk woman codesprint #2 -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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