C++ solution using array


  • 0
    S
    class Solution {
    public:
        int max(int a, int b)
        {
            return a>b?a:b;
        }
        int min(int a, int b)
        {
            return a<b?a:b;
        }
        int kEmptySlots(vector<int>& flowers, int k) {
            int n = flowers.size();
            if( n <= k)
                return -1;
            int m[20001];
            for(int i=0;i<20001;++i)
                m[i] = -1;
            int dday = INT_MAX;
            for(int i=0;i<n;++i)
                m[flowers[i]] = i;
            for(int i=0;i<20001;++i)
            {
                if(m[i] == -1 || (i+k+1) > 20000)
                    continue;
                int pos = i;
                int day = m[i];
                if(m[pos+k+1] != -1){
                    int day2 = m[pos+k+1];
                    int pos2 = pos+k+1;
                    bool f = false;
                    // make sure all flowers in between arent blooming
                    for(int j=min(pos, pos2)+1;j<max(pos, pos2);j++){
                        if(m[j] < max(day, day2))
                        {
                            f = true;
                            break;
                        }
                    }
                    
                    if(!f)
                    {
                        dday = min(dday, max(day, day2)+1);
                    }
                }
            }
            return dday==INT_MAX?-1:dday;
        }
    };
    

Log in to reply
 

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