Advertisement
sanya5791

Untitled

Apr 5th, 2023
1,059
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.02 KB | None | 0 0
  1. // Leetcode task solution: https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/
  2. class Solution {
  3.     fun minimumRounds(tasks: IntArray): Int {
  4.         val map = tasks.toCountedMap()
  5.  
  6.         var rounds = 0
  7.         map.forEach { entry ->
  8.             val minRounds = minRounds(entry.value)
  9.             if (minRounds == -1) {
  10.                 return -1
  11.             } else {
  12.                 rounds += minRounds
  13.             }
  14.         }
  15.  
  16.         return rounds
  17.     }
  18.  
  19.     private fun IntArray.toCountedMap(): Map<Int, Int> {
  20.         val map = mutableMapOf<Int, Int>()
  21.  
  22.         for (task in this) {
  23.             map[task] = (map[task] ?: 0) + 1
  24.         }
  25.         return map
  26.     }
  27.  
  28.     private fun minRounds(tasksNumber: Int): Int {
  29.         val rounds3 = tasksNumber / 3
  30.         val residue = tasksNumber % 3
  31.         return when {
  32.             residue == 1 && rounds3 == 0 -> -1
  33.             residue == 1 ||
  34.             residue == 2 -> rounds3 + 1
  35.             else -> rounds3
  36.         }
  37.     }
  38. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement