-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxDiff.java
More file actions
70 lines (54 loc) · 1.8 KB
/
Copy pathMaxDiff.java
File metadata and controls
70 lines (54 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
import java.util.ArrayList;
public class MaxDiff {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> arr = scanArray(in);
int[] index = new int[2];
index = maxDiff2(arr);
System.out.println(index[0] + " " + index[1]);
}
public static int[] maxDiff1(ArrayList<Integer> arr) {
int max = 0;
int[] res = new int[2];
for(int i=0; i<arr.size(); i++) {
for(int j=i+1; j<arr.size(); j++) {
if(arr.get(j) - arr.get(i) >= max ) {
max = arr.get(j) - arr.get(i);
res[0] = i;
res[1] = j;
}
}
}
return res;
}
public static int[] maxDiff2(ArrayList<Integer> arr) {
int min = 0;
int diff = 0;
int[] res = new int[2];
for(int i=0; i<arr.size(); i++) {
if(arr.get(i) < arr.get(min)) {
min = i;
}
if(diff < arr.get(i) - arr.get(min)) {
diff = arr.get(i) - arr.get(min);
res[0] = min;
res[1] = i;
}
}
return res;
}
public static ArrayList<Integer> scanArray(Scanner in) {
// scan line of text
String line = in.nextLine();
// convert line of text into array of strings (tokens)
String[] tokens = line.split(" ");
// convert array of strings into array of integers
ArrayList<Integer> arr = new ArrayList<Integer>();
for (String token : tokens) {
if (!token.isEmpty()) // some tokens may be empty (e.g. with trailing spaces)
arr.add(Integer.parseInt(token));
}
return arr;
}
}