Get max number with lowest number of steps

28 Views Asked by At

I have a csv with Rows of data. Each row consists of an amount_of_apples and a number of steps. The amount_of_apples are the total number of apples in a room and the steps is the distance in steps to the room.

amount_of_apples, steps
20, 8
44, 3
19, 1
12, 2
2,  8
88, 14
51, 3
59, 1
31, 8
30, 9

I would like to know what is the max number of apples I can collect if I can only travel max_steps a day e.g 100.

My current solution involves sorting the rooms by weight and then visiting each room according to weight.

weight := numberOfApples / steps

So I’d go to the room with 59 apples that’s 1 step away first and then the room with 51 apples that’s 3 steps away next. I’d then visit the next room in the list with a number of step smaller than my remaining steps and continue until I run out of rooms or steps.

current solution:

// sort rooms by weight ratio of apples to steps
sort.SliceStable(rooms, func(i, j int) bool {
        currRatio := rooms[i].numberOfApples/ rooms[i].steps
        nextRatio := rooms[j].numberOfApples / rooms[i].steps
        return currRatio > nextRatio
    })

var results []Room
    var index int
    var count float64
    var steps int
    for steps < maxSteps {
     step += rooms[index].steps
        if steps > maxSteps {
            break
        }
        results = append(results, rooms[index])
        count += rooms[index].numberOfApples
        index += 1
    }

log.Printf("The max number of apples that can be collected in %vsteps is %v", maxSteps, count)

However, I do not think this is the correct solution.