-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathTwoCityScheduling.java
65 lines (51 loc) · 1.71 KB
/
TwoCityScheduling.java
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
// @saorav21994
// TC : O(nlogn)
// SC : O(1)
// Sort the array in descending order based on difference between tarvel cost of city a and city b for ith person. Then add cost to result untill half for any one is reached, after which take the higher value as we can max make half candidates visit a particular city.
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (a,b) -> (Math.abs(b[0] - b[1]) - Math.abs(a[0] - a[1])));
int a = 0, b = 0, l = costs.length;
int resCost = 0;
for (int i = 0; i < l; i++) {
if (costs[i][0] <= costs[i][1]) {
if (a < (l/2)) {
a += 1;
resCost += costs[i][0];
}
else {
b += 1;
resCost += costs[i][1];
}
}
else {
if (b < (l/2)) {
b += 1;
resCost += costs[i][1];
}
else {
a += 1;
resCost += costs[i][0];
}
}
}
return resCost;
}
}
// Author: @romitdutta10
// TC : O(nlogn)
// SC : O(1)
// Problem: https://leetcode.com/problems/two-city-scheduling/
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (a, b) -> ((a[0] - a[1]) - (b[0] - b[1])));
int cost = 0;
for(int i=0; i<costs.length/2; i++) {
cost += costs[i][0];
}
for(int i=costs.length/2; i<costs.length; i++) {
cost += costs[i][1];
}
return cost;
}
}