Guidewire Software | virtual | Arrays

Hi All
I was given below question in codility round
A company invests its money in N projects(numbered from 0 to N-1). The K-th project has a dedicated bank account number A[K]. The first two characters of account nmuber are capital letters and represent the country code; the next six characters are digits.

The company invest B[k] in the K-th project. which country receives the most investment?

write a function

class Solution { public string solution(string[] A, int[] B);}

that, given an array A consisting of N strings representing account numbers and an array B consisting of N integers representing investments, returns a string specifying the country code of the country that recieves the most investment. if there are many possible answers, choose any one of them

Examples:

  1. Given A=["GB123456","GB789109","PL234512"] and B=[2,2,5] the function should return '"PL"
  2. Given A=["CC000000","AB000000","CC000044","DD000000"] and B=[7,10,5,8] function should return "CC"
  3. Given A=["FF123456","US123456"] and B=[12,12] function should return either FF or US

Solution:
public static string solution(string[] A, int[] B)
{

    string result=null;
     List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
     for(int i=0;i<A.Length;i++)
     {
         list.Add(new KeyValuePair<string, int>(A[i].Substring(0,2),B[i] ));
         
     }
      var pair = list.OrderByDescending(x => x.Value).First();
      result=pair.Key;
      IEnumerable<IGrouping<string, KeyValuePair<string, int>>> duplicateKVPsByKey = list.GroupBy(kvp => kvp.Key).Where(g => g.Count() > 1);
     int total=0;
     string res2=null;
    foreach (var group in duplicateKVPsByKey)
    {
        res2=group.Key;
       foreach (var kvp in group)
        {
            total+=kvp.Value;
        }
    } 
    if(pair.Value>total)
    {
        result=pair.Key;
    }
    else
    {
        result=res2;
    }


    return result;
}
Comments (8)