A similar question has been asked here. But it is concerned with the scatter plot. I want to achieve the same with simple line plot. I know there are solutions for drawing multicolored line but I'm not interested in that.
I want something like below where maxima and minima are clearly distinguishable by color:

In this stackoverflow answer provides a very close solution however it is not generic, it works on predefined functions, does not work on dataset.
In R it is doable using ggplot2 (Source)
Is there any way to achieve this?