-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNthStatisitc.java
More file actions
72 lines (62 loc) · 1.65 KB
/
NthStatisitc.java
File metadata and controls
72 lines (62 loc) · 1.65 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
package hackpack;
public class NthStatisitc {
public int[] getKMedians(int k, int[] nums){
// median of an array is n/2
// k/2 before the median is n/2-k/2 = (n-k)/2
// k/2 after median is n/2+k/2 = (n+k/2)
// Get statistic of (n-k)/2
int upper = getNthStatistic((nums.length-k)/2,nums,0,nums.length-1);
// Get statistic of (n+k)/2
int lower = getNthStatistic((nums.length+k)/2,nums,0,nums.length-1);
// Loop through array and save items that are between upper and lower
int[] answers = new int[k];
int counter = 0;
for(int i = 0; i < nums.length || counter < k;i++){
if(nums[i] >= upper && nums[i] <= lower){
answers[counter++] = nums[i];
}
}
return answers;
}
public int getNthStatistic(int n, int[] nums, int start, int end) {
int pivot = nums[end];
int left = start;
int right = end;
// Loop through partitioner
while (true) {
while (nums[left] < pivot && left < right) {
left++;
}
while (nums[right] >= pivot && right > left) {
right--;
}
if (left == right) {
break;
}
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
int temp = nums[left];
nums[left] = nums[end];
nums[end] = temp;
if (n == left+1) {
return pivot;
}else if (n < left+1) {
return getNthStatistic(n, nums, start, left-1);
}else {
return getNthStatistic(n, nums, left+1, end);
}
}
public int cutRods(int[] prices, int n, int cost){
int[] bests = new int[n+1];
for(int i = 0; i <= n; i++){
int curMax = prices[i];
for(int j = 1; j < i; j++){
curMax = Math.max(curMax, prices[i] + bests[i-j] - cost);
}
bests[i] = curMax;
}
return bests[n];
}
}