1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00

cs: add «539. Minimum Time Difference»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-16 19:53:03 +02:00
parent 967ca0f1a2
commit 11f539ddd6
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,42 @@
using System.Collections.Immutable;
public class Solution {
private record Time(int hours, int minutes) {
public int Normalized { get => hours * 60 + minutes; }
public static int Distance(Time a, Time b) =>
Math.Abs(b.Normalized - a.Normalized);
public static bool TryParse(string? s, out Time time) {
if (s == null) {
goto TimeFailedTryParse;
}
var parts = s.Split(":");
if (parts.Length != 2) {
goto TimeFailedTryParse;
}
if (int.TryParse(parts[0], out var hours) && int.TryParse(parts[1], out var minutes)) {
time = new Time(hours, minutes);
return true;
}
TimeFailedTryParse:
time = new Time(0, 0);
return false;
}
}
public int FindMinDifference(IList<string> timePoints) {
var times = timePoints.Select(t => {
Time.TryParse(t, out var time);
return time;
}).OrderBy(time => time.Normalized).ToImmutableList();
return Math.Min(
24 * 60 - Time.Distance(times.Last(), times.First()),
times.Zip(times.Skip(1)).Select(pair => Time.Distance(pair.First, pair.Second)).Min()
);
}
}