-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacentValues.java
More file actions
96 lines (74 loc) · 1.49 KB
/
Copy pathAdjacentValues.java
File metadata and controls
96 lines (74 loc) · 1.49 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.Arrays;
public class AdjacentValues
{
// http://www.careercup.com/question?id=5653018213089280
public static void main(String[] args) {
int[] a = {1,1,1,2,1,1,1};
int n = 1;
AdjacentValues x = new AdjacentValues();
System.out.println(x.minAdgSum(a, n));
}
private int minAdgSum(int[] a, int n) {
// find the largest number
int maxIndex = findMax(a);
// add outwards from the largest number
a = countOut(a, maxIndex);
// System.out.println(Arrays.toString(a));
int min = Integer.MAX_VALUE;
int minIndex = Integer.MIN_VALUE;
// look right
for(int i = maxIndex; i < a.length; i++)
{
if(a[i] >= n)
{
min = a[i];
minIndex = i;
break;
}
}
// System.out.println(maxIndex + " " + minIndex);
// look left
for(int i = maxIndex; i >= 0; i--)
{
if(a[i] >= n)
{
min = a[i];
minIndex = i;
break;
}
}
// System.out.println(maxIndex + " " + minIndex);
// if not found
if(minIndex == Integer.MIN_VALUE)
return 0;
return Math.abs(maxIndex - minIndex) + 1;
}
public int findMax(int[] a)
{
int max = -1;
int ind = -1;
for(int i = 0; i < a.length; i++)
{
if(a[i] > max)
{
max = a[i];
ind = i;
}
}
return ind;
}
public int[] countOut(int[] a,int start)
{
// right
for(int i = start; i < a.length - 1; i++)
{
a[i + 1] = a[i] + a[i + 1];
}
// left
for(int i = start; i > 0; i--)
{
a[i - 1] = a[i] + a[i - 1];
}
return a;
}
}