The Below code is to find the count of highest number in a array. but it is not working

Viewed 74

I am trying to get a highest number count using GO CODE below but i seems to be not working. which is a simple program but i was unable to get the correct answer which is 2 in this case.

package main

import (
    "fmt"
)

func main() {
    fmt.Print(findLargeNumberCount([]int32{4, 4, 1, 3}))
}

func findLargeNumberCount(candles []int32) int32 {
    var highest int32 = 0
    var prev int32 = candles[0]
    for i := 1; i < len(candles); i++ {
        if prev == candles[i] {
            highest++
        } else if candles[i] > prev {
            highest = 1
            
        }
        prev = candles[i]
    }
    return highest
}
1 Answers

You should change your code to have it works:

package main

import (
    "fmt"
)

func main() {
    fmt.Print(findLargeNumberCount([]int32{4, 4, 1, 3}))
}

func findLargeNumberCount(candles []int32) int32 {
    var highest int32 = 1
    var prev int32 = candles[0]
    for i := 1; i < len(candles); i++ {
        if prev == candles[i] {
            highest++
        } else if candles[i] > prev {
            prev = candles[i]
            highest = 1

        }
    }
    return highest
}

https://go.dev/play/p/0OnUiGnfKXI

What was changed:

  1. var highest int32 = 1 , not 0
  2. prev = candles[i] should be in else if block

Explanation:

Assume, that the first element of the slice(candles in code) is the highest one (prev in code) and set the count of the highest number to 1 (highest in code).

After that start iterating over the slice:

If we have an element of the slice (candles[i] in code) that is equal to the current highest(prev) then we increase the highest number count (highest),

else if we have an element (candles[i]) that is higher than the current highest (prev) we assign new current highest prev = candles[i] and reset the highest number count to 1 highest = 1 and keep iterating till the end of the slice.

Related