Each visitor stays for one time unit at a distinct arrival time; with at most K lights, minimize total stove-on time by skipping the largest idle gaps.
Medium5GreedySortingIntervalsInterviewNo attempts yetTime limit1sMemory limit256 MBJiho has one stove in the room. To save fuel he keeps it off while he is alone, but the stove is always on while a friend is in the room.
Today N friends come to Jiho's place. He numbers them 1 to N so he can tell them apart. Friend i arrives at time Ti and leaves at time Ti+1. The room is small, so only one friend fits at a time. That is, the room never holds more than two people, Jiho included.
Jiho can turn the stove on and off at any moment. Lighting it takes one match, and he has K matches today, so he can light the stove at most K times. The stove starts out off.
Jiho wants the stove to burn for as little total time as possible. Given the arrival times of the friends and the number of matches, write a program that computes the minimum total time the stove is on.
The first line contains the number of friends N (1≤N≤105) who visit Jiho and the number of matches K (1≤K≤N) that he has.
Each of the next N lines contains the arrival time Ti of friend i, in increasing order of i (1≤Ti≤109). No two friends arrive at the same time, so Ti<Ti+1 holds for every 1≤i≤N−1.
Print the minimum total time the stove is on.
One friend can leave at the same time as the next friend arrives. Putting the stove out and lighting it again at that moment leaves the burning time unchanged and costs one more match.
With N matches Jiho can light the stove at every arrival and put it out at every departure. With a single match he has to light it when the first friend arrives and leave it burning until the last friend leaves.