ORIGINAL CODING QUESTION
Course list with follow-on discounts
Courses are listed in order with integer prices. Each course is discounted by the price of the first course listed after it whose price is less than or equal to its own. A course with no such later course gets no discount. Return the total amount paid for all courses after the discounts.
Original exercise · easy. Editorial role relevance does not imply a company has asked this question.
Input and output
n, then n prices. Print the total paid.
Constraints
1 ≤ n ≤ 200; 0 ≤ price ≤ 1000.
Example 1
Input
5 8 4 6 2 3
Output
15
Payments are 8-4, 4-2, 6-2, 2 and 3, totalling 15.
Example 2
Input
4 1 2 3 4
Output
10
No later price is lower or equal, so nothing is discounted.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
Checking every later course for each course is quadratic.
Hint 2
Keep a stack of earlier courses that have not found their discount yet.
Hint 3
When a price arrives, pop every stacked course whose price is at least it, discount those courses by the new price, then push the new course.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →