Leetcode - letter-case-permutation
Leetcode - ugly-number-ii

Leetcode - maximize-distance-to-closest-person

violet posted @ Mar 17, 2020 12:35:39 AM in 算法 with tags Algorithm array Golang , 307 阅读

https://leetcode.com/problems/maximize-distance-to-closest-person/

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. 

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. 

Return that maximum distance to closest person.

Example 1:

Input: [1,0,0,0,1,0,1]
Output: 2
Explanation: 
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

 

Prepare two arrays. One is to calculate the left distance for every seat, another is to calculate the right distance for every seat. And then iterate these two arrays and peak minimum one in two distances, tracking for maximum one.

func maxDistToClosest(seats []int) int {
    arr1 := make([]int, len(seats))
    arr2 := make([]int, len(seats))
       
    prev := -30000
    for i := 0; i < len(seats); i++ {
        if seats[i] == 1 {
            arr1[i] = 0
            prev = i
        } else {
            arr1[i] = i - prev
        }
    }
    prev = 30000
    for i := len(seats)-1; i >= 0; i-- {
        if seats[i] == 1 {
            arr2[i] = 0
            prev = i
        } else {
            arr2[i] = prev - i
        }
    }
    
    maxDistance := math.MinInt32
    
    for i := 0; i < len(seats); i++ {
        currDistance := min(arr1[i], arr2[i])
        if maxDistance < currDistance {
            maxDistance = currDistance
        }
    }
    
    
    return maxDistance
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter