Goodland Electricity

  • + 0 comments

    C#:

    public static int pylons(int k, List<int> arr)
        {
            int p = -1;
            int count = -1;
            p = StartingKIndex(p, arr, k);
            if(p != -1)
            {
                p = MiddleIndexes(p, k, arr, out count);
            }
            if(count != -1 && (p + k - 1) < arr.Count - 1)
            {
                p = arr.Count - 1;
                count  = LastIndex(p, k, arr, count); 
            }
            return count;
        }
        
        public static int StartingKIndex(int p, List<int> arr, int k)
        {
            // Check the first city where Power plant can be built within the distribution range
            
            for(int i = k - 1; i >= 0; i--)
            {
                if(arr[i] == 1)
                {
                    p = i; 
                    break;
                }
            }
            
            return p;
        }
        
        public static int MiddleIndexes(int p, int k, List<int> arr, out int count)
        {   
            // StartIndex function will return a city index so make the count as 1 initially.
            count = 1;
            
            // Check for the next cities where Power plant can be built and increment the count
            while((p + (2 * k) - 1) < arr.Count)
            {
                bool flag = false;
                p = p + (2 * k) - 1;
                for(int i = p; i > p - (2 * k) + 1; i--)
                {
                    if(arr[i] == 1)
                    {
                        p = i;
                        count = count + 1;
                        flag = true;
                        break;
                    }
                }
                
            // if a city cannot be covered withing the distribution range make the count as -1
                if(!flag)
                {
                    count = -1;
                    break;
                }
            }
            return p;
        }
        
        public static int LastIndex(int p, int k, List<int> arr, int count)
        {
         // find the last city where the power plant can be built within the distribution range.   
            
            bool flag = false;
            for(int i = p; i > arr.Count - k + 1; i--)
            {
                if(arr[i] == 1)
                {
                    count += 1;
                    flag = true;
                    break;
                }
            }
            
            // if city is not found make the count as -1
            if(!flag)
            {
                count = -1;
            }
            return count;
        }