2483. Minimum Penalty for a Shop

Difficulty:
Related Topics:
Similar Questions:

Problem

You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':

If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:

Return** the earliest hour at which the shop must be closed to incur a minimum penalty.**

Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.

  Example 1:

Input: customers = "YYNY"
Output: 2
Explanation: 
- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.

Example 2:

Input: customers = "NNNNN"
Output: 0
Explanation: It is best to close the shop at the 0th hour as no customers arrive.

Example 3:

Input: customers = "YYYY"
Output: 4
Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.

  Constraints:

Solution (Java)

class Solution {
    public int bestClosingTime(String s) {
        int n=s.length();
        int [] a1 = new int[n];
        int [] a2 = new int[n];
        char[] a3 = s.toCharArray();
        if(a3[0]=='N')
        {
            a2[0]++;
        }
        for(int i=1;i<n;i++)
        {
            if(a3[i]=='N')
            {
                a2[i]++;
            }
            a2[i]+=a2[i-1];
        }
        if(a3[n-1]=='Y')
        {
            a1[n-1]++;
        }
        for(int i=n-2;i>=0;i--)
        {
            if(a3[i]=='Y')
            {
                a1[i]++;
            }
            a1[i]+=a1[i+1];
        }

        int m=10000000;
        int index=-1;
        for(int i=0;i<n;i++)
        {
            int p = a1[i];
            int pr=0;
            if(i-1>=0)
            {
                pr = a2[i-1];
            }
            p+=pr;
            if(p<m)
            {
                m=p;
                index=i;
            }
        }
        return a2[n-1]<m ? n : index;
    }
}

Explain:

nope.

Complexity: