Regarding the code written

Sir why should we use that -1 in finding the index. Although i know without it answer is not coming right, but if we have used comparator of a<=b, so in 120 shouldn’t it return 100? (as 100<=120).

can you share the Complete code?

which question you are asking??
money change problem ??
your code is of priority queue

#include #include using namespace std; bool compare(int a, int b){ return a<=b; } int main() { int coins[]={0,2,5,10,20,50,100,200,500,2000}; int n=sizeof(coins)/sizeof(int); int money=120; while(money>0){ int lb=lower_bound(coins,coins+n,money,compare)-coins-1; cout<<coins[lb]<<","; money=money-coins[lb]; } }

how can i read this
plz share the link of code
so that i can run and edit to check your code

the comparator return value indicates whether the first argument is considered to go before the second.
as 100<=120 holds true so iteration moves ahead 200<=120 fails hence return 200
lower_bound(coins,coins+n,money,compare) this will give 200 not 120
hence we have to subtract 1 to get desired results

to avoid such confusions
best way is to
first print what lower_bound(coins,coins+n,money,compare) this will give and then write accordingly

cout<<*lower_bound(coins,coins+n,money,compare)<<endl;

got your point that since it is returning one greater index so we subtracted 1, then in case when money will be 100, then why subtracting 1 is still giving the right answer?

for money =100 it still return 200 check this


cout<<*lower_bound(coins,coins+n,money,compare)<<endl;