We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Simple Java approach by buying the flowers backward from the most expensive to least expensive:
importjava.io.*;importjava.util.*;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scanners=newScanner(System.in);intn=s.nextInt();intk=s.nextInt();int[]flowers=newint[n];for(inti=0;i<n;i++){flowers[i]=s.nextInt();}System.out.println(CalculateMinPrice(flowers,k));}staticintCalculateMinPrice(int[]flowers,intk){//sort all flower prices in ascending orderArrays.sort(flowers);inti=flowers.length-1;intbought=0;inttotal=0;//start backwards from the most expensive flower, stop when there is no more flowers leftwhile(i>=0){//Calculate total //increment bought by 1 when everyone in the group has bought equal number of flowersfor(intj=0;j<k&&i>=0;j++){total+=(1+bought)*flowers[i];i--;}bought++;}returntotal;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Greedy Florist
You are viewing a single comment's thread. Return to all comments →
Simple Java approach by buying the flowers backward from the most expensive to least expensive: