![JAR search and dependency download from the Maven repository](/logo.png)
g2201_2300.s2256_minimum_average_difference.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g2201_2300.s2256_minimum_average_difference
// #Medium #Array #Prefix_Sum #2023_06_28_Time_527_ms_(100.00%)_Space_52.1_MB_(100.00%)
class Solution {
fun minimumAverageDifference(nums: IntArray): Int {
var numsSum: Long = 0
for (num in nums) {
numsSum += num.toLong()
}
var minAverageDiff = Long.MAX_VALUE
var sumFromFront: Long = 0
var index = 0
for (i in nums.indices) {
sumFromFront += nums[i].toLong()
val numbersRight = if (i == nums.size - 1) 1 else nums.size - i - 1
val averageDiff = Math.abs(sumFromFront / (i + 1) - (numsSum - sumFromFront) / numbersRight)
if (minAverageDiff > averageDiff) {
minAverageDiff = averageDiff
index = i
}
if (averageDiff == 0L) {
break
}
}
return index
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy