Can't Find the Error in My Logic

I do these daily coding challenges that come to my email each day.
Today has me stumped and I can’t figure out what I am missing in my logic.

Here is the prompt:

You are given an array representing the heights of neighboring buildings on a city street, from east to west. The city assessor would like you to write an algorithm that returns how many of these buildings have a view of the setting sun, in order to properly value the street.

For example, given the array [3, 7, 8, 3, 6, 1], you should return 3, since the top floors of the buildings with heights 8, 6, and 1 all have an unobstructed view to the west.

You can find my current code at this playground link:
https://play.golang.org/p/emo3-17FAnI

When adding fmt.Println(buildings[currentIdx] directly before return count + 1 in the “helper” function it shows that it is correctly finding the indexes that it should return an increased count for but the end result is still too high.

Any insight is very much appriciated.
:nerd_face:

1 Like

That’s easy - your recursive call do nothing. Just add return statement before calling helper and that’s it.

But it can be simplified. All that you need to solve the task - find count updates of maximum value when traverse from east to west.

2 Likes

I would keep it simple ant iterate all items reverse order, and compare the highest and the current height. If the current height greater than the highest it can see the sun.

import "fmt"

var buildings = []int{1, 9, 8, 3, 5, 6, 7, 2}

func main() {
	heighest := 0
	sunViews := []int{}
	for i := len(buildings) -1; i >= 0; i-- {
		h := buildings[i]
		if h > heighest {
			sunViews = append(sunViews, h)
			heighest = h
		}
	}
	for _, h := range sunViews {
		fmt.Println(h)
	}
}

https://play.golang.org/p/cfrtb7S1jDG

3 Likes

Who is sending the challenges? I would like to see them too.

2 Likes

Thanks @GreyShatter and @kync I knew it was going to be something simple. :sweat_smile:

@kync the site is https://www.dailycodingproblem.com/ you can even pay $8/month and they will send solutions the next day. But even if you don’t pay the daily problems are free.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.