Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Solution
- {
- const int SECONDS_PER_5_MINUTES = 300;
- const int SECONDS_PER_HOUR = 3600;
- const int SECONDS_PER_MINUTE = 60;
- const int MINUTES_PER_HOUR = 60;
- public int solution(string S)
- {
- //Have to separate between time of each call and price of each call, since a call of 7 minutes
- //it's not the same as 7 calls of 1 minute. We could have done this with quite a lot of structures,
- //I chose dictionaries for simplicity
- Dictionary<int, TimeSpan> callsTimeTable = new Dictionary<int, TimeSpan>();
- Dictionary<int, long> callsPricingTable = new Dictionary<int, long>();
- foreach (string call in S.Split('n'))
- {
- ProcessCall(call, callsTimeTable, callsPricingTable);
- }
- //Here, I could do the typical algorithm searching for the max value looping the different timespans
- //"if (value > max) max = value"
- //Could do the same a few lines below with the Min function
- TimeSpan maxTotalCalls = callsTimeTable.Values.Max();
- List<int> maxTotalCallsNumbers = callsTimeTable.Where(v => v.Value == maxTotalCalls).Select(kv => kv.Key).ToList();
- if (maxTotalCallsNumbers.Count == 1)
- callsPricingTable.Remove(maxTotalCallsNumbers.First());
- else
- {
- int minPhoneNumber = maxTotalCallsNumbers.Min();
- callsPricingTable.Remove(minPhoneNumber);
- }
- //I assume that, if we have only one number in the dictionary, this has the longest total duration, so it's free.
- if (callsPricingTable.Count == 0) return 0;
- return (int)callsPricingTable.Values.Max();
- }
- private void ProcessCall(string call, Dictionary<int, TimeSpan> callsTimeTable, Dictionary<int, long> callsPricingTable)
- {
- //dictionaries are reference types, so no ref keyword needed
- string[] timeNumber = call.Split(',');
- int phoneNumber = Convert.ToInt32(timeNumber[1].Replace("-", ""));
- string[] hhmmss = timeNumber[0].Split(':');
- TimeSpan actualTimeCall = new TimeSpan(Convert.ToInt32(hhmmss[0]), Convert.ToInt32(hhmmss[1]), Convert.ToInt32(hhmmss[2]));
- if (!callsTimeTable.ContainsKey(phoneNumber))
- {
- callsTimeTable.Add(phoneNumber, actualTimeCall);
- callsPricingTable.Add(phoneNumber, ProcessCallPricing(actualTimeCall));
- }
- else
- {
- TimeSpan allTimeCall = callsTimeTable[phoneNumber];
- callsTimeTable[phoneNumber] = allTimeCall.Add(actualTimeCall);
- callsPricingTable[phoneNumber] += ProcessCallPricing(actualTimeCall);
- }
- }
- private long ProcessCallPricing(TimeSpan callTime)
- {
- //TimeSpan have a TotalSeconds property, but for the exercise, seconds will be calculated manually
- long seconds = callTime.Hours * SECONDS_PER_HOUR + callTime.Minutes * SECONDS_PER_MINUTE + callTime.Seconds;
- if (seconds < SECONDS_PER_5_MINUTES)
- {
- return seconds * 3;
- }
- return (callTime.Hours * MINUTES_PER_HOUR + callTime.Minutes + (callTime.Seconds > 0 ? 1 : 0)) * 150;
- }
- }
Add Comment
Please, Sign In to add comment