Repository navigation
Expand file tree
/
Copy pathSolution3.java
More file actions
111 lines (89 loc) · 2.22 KB
/
Copy pathSolution3.java
File metadata and controls
111 lines (89 loc) · 2.22 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package woowa;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
public class Solution3 {
public int solution(int[] A, int[] B, int M, int X, int Y) {
// write your code in Java SE 8
int count = 0;
List<Person> people = new ArrayList<>();
createPeople(A, B, people);
List<Person> inElevator = new ArrayList<>();
while (!people.isEmpty()) {
Person p = people.get(0);
inElevator.add(p);
if (!check(inElevator, X, Y)) {
inElevator.remove(p);
count += run(inElevator);
} else {
people.remove(p);
}
}
if (!inElevator.isEmpty())
count += run(inElevator);
return count;
}
private void createPeople(int[] A, int[] B, List<Person> people) {
for (int i = 0; i < A.length; i++) {
people.add(new Person(A[i], B[i]));
}
}
private int run(List<Person> inElevator) {
int count = 0;
Set<Integer> visit = new HashSet<>();
for (Person passenger : inElevator) {
visit.add(passenger.getDestination());
}
count += visit.size();
count += 1;
inElevator.clear();
return count;
}
private boolean check(List<Person> people, int X, int Y) {
return checkCount(people, X) && checkWeight(people, Y);
}
private boolean checkCount(List<Person> people, int limit) {
return people.size() <= limit;
}
private boolean checkWeight(List<Person> people, int limit) {
int sum = 0;
for (Person p : people) {
sum += p.getWeight();
if (sum > limit)
return false;
}
return true;
}
@Test
public void test() {
int[] A = {60, 80, 40, 40};
int[] B = {1, 2, 1, 2};
int M = 3;
int X = 2;
int Y = 100;
System.out.println(solution(A, B, M, X, Y));
}
}
class Person {
private int weight;
private int destination;
public Person(int weight, int destination) {
this.weight = weight;
this.destination = destination;
}
public int getWeight() {
return weight;
}
public int getDestination() {
return destination;
}
@Override
public String toString() {
return "Person [weight=" + weight + ", destination=" + destination + "]";
}
}