PS/LeetCode
[Kotlin] LeetCode 2079 : Watering Plants
뱃싸공
2022. 12. 3. 16:57
Watering Plants - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
간단한 시뮬레이션 문제입니다.
현재 가지고 있는 물의 상태로 다음 칸을 채울 수 있다면 굳이 돌아갈 필요가 없겠죠. 반면 부족하다면 무조건 돌아가야 합니다.
돌아갈 필요가 없는 경우는 정답에 +1을 해주면 되고 돌아가야 하는 경우에는 현재 위치를 i라고 할때 2*i+1 만큼 이동하도록 구현해주면 됩니다.
class Solution {
fun wateringPlants(plants: IntArray, capacity: Int): Int {
var answer : Int = 0
var current : Int = capacity
for (i in plants.indices) {
if (isPossible(plants[i], current)) {
answer++
current -= plants[i]
}
else {
answer += getMoving(i)
current = capacity - plants[i]
}
}
return answer
}
fun isPossible(a : Int, b : Int) = (a <= b)
fun getMoving(num : Int) = (2*num + 1)
}