-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
63 lines (51 loc) · 1.47 KB
/
Copy pathsolution.java
File metadata and controls
63 lines (51 loc) · 1.47 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
class Solution {
// Function to calculate GCD
private int gcd(int a, int b) {
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
// Simulate pouring from one jug to another
private int pour(int fromCap, int toCap, int d) {
int from = fromCap;
int to = 0;
int steps = 1; // Filling source jug
while (from != d && to != d) {
// Transfer water
int transfer = Math.min(from, toCap - to);
to += transfer;
from -= transfer;
steps++;
// If target found
if (from == d || to == d) {
break;
}
// Refill source jug if empty
if (from == 0) {
from = fromCap;
steps++;
}
// Empty target jug if full
if (to == toCap) {
to = 0;
steps++;
}
}
return steps;
}
public int minSteps(int m, int n, int d) {
// Impossible if d is larger than both jugs
if (d > Math.max(m, n)) {
return -1;
}
// Impossible if d is not divisible by gcd
if (d % gcd(m, n) != 0) {
return -1;
}
// Minimum of both possible directions
return Math.min(pour(m, n, d), pour(n, m, d));
}
}