1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-21 10:36:56 +02:00
LeetCode/cs/minimum-time-difference.cs
Matej Focko 11f539ddd6
cs: add «539. Minimum Time Difference»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-09-16 19:53:03 +02:00

42 lines
1.3 KiB
C#

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()
);
}
}