LeetCode in Kotlin

2483. Minimum Penalty for a Shop

Medium

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 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

class Solution {
    fun bestClosingTime(customers: String): Int {
        val yes = IntArray(customers.length + 1)
        val no = IntArray(customers.length + 1)
        var count = 0
        for (i in customers.length - 1 downTo 0) {
            if (customers[i] == 'Y') {
                count++
            }
            yes[i] = count
        }
        count = 0
        for (i in 0 until customers.length) {
            if (customers[i] == 'N') {
                count++
            }
            no[i + 1] = count
        }
        var min = Int.MAX_VALUE
        var res = 0
        for (i in yes.indices) {
            val sum = yes[i] + no[i]
            if (min > sum) {
                min = sum
                res = i
            }
        }
        return res
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy