Int 3 for Programmers

The fastest stretch of growth

The fastest stretch of growth

A greenhouse records the height of a plant in millimetres, always the same number of days apart. You are asked which stretch between two consecutive readings had the fastest growth, and how fast that was.

Write fastest_growth(heights, gap), which returns the largest average rate of change between two consecutive readings, in millimetres per day. gap is the number of days between readings.

rate for one stretch=later height−earlier heightgap\text{rate for one stretch} = \frac{\text{later height} - \text{earlier height}}{\text{gap}}

Worked example, with heights = [40, 110, 180, 240] and gap = 7. The three stretches give 110−407=10\frac{110-40}{7} = 10, 180−1107=10\frac{180-110}{7} = 10 and 240−1807≈8.571\frac{240-180}{7} \approx 8.571. The largest is 10, so the answer is 10.

  • Constraints: heights has at most 50 entries, and gap is between 1 and 30.
  • Heights may fall as well as rise, so a rate can be negative. Return the largest one, which may still be negative.
  • If there are fewer than two readings there is no stretch at all, so return 0.
  • Answers are compared with a small tolerance, so an ordinary division is fine. Take care in a language where dividing two whole numbers throws the fraction away.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.