- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of n elements. These are the ratings of them. Find the minimum cost to buy all books, with the following condition −

- Cost of each book would be at-least 1 dollar
- A book has higher cost than an adjacent (left or right) if rating is more than the adjacent.

So for example, if the rating array is like [1, 3, 4, 3, 7, 1], Then the output is 10, As 1 + 2 + 3 + 1 + 2 + 1 = 10

To solve this, we have to make two arrays called LtoR, and RtoL, and fill them with 1, now follow these steps −

- Traverse left to right, then fill LtoR, and update it by seeing previous rating of the given array. We are not caring about the next rating of given array
- Traverse right to left, then fill RtoL, and update it by seeing previous rating of the given array. We are not caring about the next rating of given array
- For maximum value of ith position in both array LtoR and RtoL, then add it to the result.

#include<iostream> using namespace std; int getMinCost(int ratings[], int n) { int res = 0; int LtoR[n]; int RtoL[n]; for(int i = 0; i<n; i++){ LtoR[i] = RtoL[i] = 1; } for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) LtoR[i] = LtoR[i - 1] + 1; for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) RtoL[i] = RtoL[i + 1] + 1; for (int i = 0; i < n; i++) res += max(LtoR[i], RtoL[i]); return res; } int main() { int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 }; int n = sizeof(ratings) / sizeof(ratings[0]); cout << "Minimum cost is: " << getMinCost(ratings, n); }

Minimum cost is: 15

- Related Questions & Answers
- Program to find minimum cost to connect all points in Python
- Find the minimum and maximum amount to buy all N candies in Python
- Program to Find Out the Minimum Cost to Purchase All in Python
- Find minimum adjustment cost of an array in C++
- Minimum Cost to Connect Sticks in C++
- Minimum Cost to Merge Stones in C++
- Minimum Cost For Tickets in C++
- Minimum Cost to Hire K Workers in C++
- C Program for Minimum Cost Path
- Find minimum adjustment cost of an array in Python
- Minimum Cost Polygon Triangulation
- Minimum Cost To Make Two Strings Identical in C++
- Find the minimum cost to reach destination using a train
- Find minimum speed to finish all Jobs in C++
- Program to find minimum deletion cost to avoid repeating letters in Python

Advertisements