share my java solution, greedy method which is very similar to rearrage String problem!


  • 0
    T
    public class Solution {
        public int leastInterval(char[] tasks, int n) {
            int[] count=new int[26];
            for(int i=0;i<tasks.length;i++){
                count[tasks[i]-'A']++;
            }
            
            
            int[] valid=new int[26];
            int step=0;
            
            for(int i=0;i<tasks.length;i++){
                boolean check=false;
                while(!check){
                     check=findTask(valid,count,step,n);
                     step++;
                }
            }
            return  step;
        }
        
        public boolean findTask(int[] valid,int[] count,int index,int n){
            boolean check=false;
            int max_cnt=Integer.MIN_VALUE;
            int target_ind=-1;
            
            for(int i=0;i<26;i++){
                if(count[i]>0&&index>=valid[i]&&max_cnt<count[i]){
                    max_cnt=count[i];
                    target_ind=i;
                    check=true;
                }
            }
            if(check==true){
                valid[target_ind]=index+n+1;
                count[target_ind]--;
            }
            return check;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.