Wednesday, April 14, 2021

Published April 14, 2021 by Anonymous with 0 comment

Minimize cost to convert all occurrences of each distinct character to lowercase or uppercase

import java.io.*;

import java.lang.*;

import java.util.*;

class GFG{

static void minimumCost(String str, int L, int U)

{

     

    

    int N = str.length();

    char s[] = str.toCharArray();

    String ans = "";

    

    

    int lowerFreq[] = new int[26];

    int upperFreq[] = new int[26];

    

    for(int i = 0; i < N; i++)

    {

         

        

        

        if (Character.isUpperCase(s[i]))

            upperFreq[s[i] - 'A']++;

        

        

        else

            lowerFreq[s[i] - 'a']++;

    }

    

    

    int result[] = new int[26];

    

    for(int i = 0; i < 26; i++)

    {

         

        

        

        if (lowerFreq[i] != 0 || upperFreq[i] != 0)

        {

             

            

            

            

            int costToUpper = U * lowerFreq[i];

            int costToLower = L * upperFreq[i];

            

            

            if (costToLower < costToUpper)

            {

                result[i] = 1;

            }

        }

    }

    

    for(int i = 0; i < N; i++)

    {

         

        

        

        int index = 0;

        if (Character.isLowerCase(s[i]))

            index = s[i] - 'a';

        else

            index = s[i] - 'A';

        

        

        

        if (result[index] == 1)

        {

             

            

            s[i] = Character.toLowerCase(s[i]);

        }

        else

        {

             

            

            s[i] = Character.toUpperCase(s[i]);

        }

    }

    

    System.out.println(new String(s));

}

public static void main(String[] args)

{

    String S = "aabbAA";

    int L = 1, U = 1;

    minimumCost(S, L, U);

}

}

Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment