Skip to content

Instantly share code, notes, and snippets.

@Tokiyomi
Created October 24, 2022 07:15
Show Gist options
  • Save Tokiyomi/b980e655f9dbc01148a8e3132e53fccd to your computer and use it in GitHub Desktop.
Save Tokiyomi/b980e655f9dbc01148a8e3132e53fccd to your computer and use it in GitHub Desktop.
// Solve sum in Kotlin
fun solve_sum(A:MutableList<Long>, B:MutableList<Long>):MutableList<Long> {
/*
This function implements a greedy approach to minimize the sum difference
among two sets A and B
*/
var C = A + B
C = C.sortedDescending().toMutableList()
var a_sum:Long = 0L
var b_sum:Long = 0L
var equal_sum_set = mutableListOf<Long>() // generate empty list to store resulting set
for (i in C.indices) {
if (a_sum > b_sum) {
b_sum += C[i]
equal_sum_set.add(C[i])
} else {
a_sum += C[i]
}
}
return equal_sum_set
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment