I am trying to solve an algorithm for finding max subarray in an array, using the max() function that compares 2 Ints and returns the bigger value.
I looked at other questions on stack overflow and no one refers to this problem so I must be doing something very basic wrong here. Also looked at the .math Library on Kotlin:
To try and understand but again, I put two Ints in a max() function and I keep getting type mismatch as it requires a Boolean.
I even went and created my own function (maxCustom()) in the code below to try and bypass that, stating specifically that it receives two Ints and returns an Int, and I still get the same Boolean type mismatch.
fun maximumSubarray(nums: List<Int>): Int {
fun maxCustom(a: Int, b: Int): Int {
return if (a > b) a
else b
}
var maxGlobal = 0
var maxCurrent = maxGlobal == nums[0]
for (num in nums[1] .. nums[nums.size-1]) {
maxCurrent = maxCustom(a = nums[num], b = maxCurrent nums[num])
if (maxCurrent > maxGlobal) {
maxGlobal = maxCurrent
}
}
return maxGlobal
}
fun main() {
val nums = listOf(-2, 3, 2, -1)
val solution = maximumSubarray(nums)
println(solution)
}
Thanks for the help
CodePudding user response:
As @Sam points out, your maxCurrent
variable is a Boolean, not an Integer. As such, when you try to assign an Integer to maxCurrent
, it fails.
To avoid such errors in the future, you should instantiate your variables with types using syntax such as var maxCurrent: Int = maxGlobal
.
N.B.: For this particular problem it would be better to instantiate your maxGlobal
with a declaration such as var maxGlobal: Int = Int.MIN_VALUE
. This is the minimum value an Int can have. You should do this as the maximum subarray could be less than 0!