A group of friends wants to buy a bouquet of flowers. The florist wants to maximize his number of new customers and the money he makes. To do this, he decides he'll multiply the price of each flower by the number of that customer's previously purchased flowers plus 1. The first flower will be the original price, the next will be, and so on.
Given the size of the group of friends, the number of flowers they want to purchase, and the original prices of the flowers, determine the minimum cost to purchase all of the flowers.
Given the size of the group of friends, the number of flowers they want to purchase, and the original prices of the flowers, determine the minimum cost to purchase all of the flowers.
Example:
Input: n=5, k = 3, arr[]={1,3,5,7,9}
Output: 29
Approach
Java
public class GreedyFlorist {public static void main(String[] args) {int k = 3;int arr[] = { 1, 3, 5, 7, 9 };int res = getMinimumCost(k, arr);System.out.println(res);}static int getMinimumCost(int k, int[] arr) {int n = arr.length;arr = selectionSorting(arr, n);int ans = 0;int l = 0;for (int i = 0; i < Math.min(k, n); i++) {ans = (ans + (1 + l) * arr[i]);}l++;int cnt = 0;for (int i = k; i < n; i++) {ans = (ans + (1 + l) * arr[i]);cnt++;if (cnt == k) {cnt = 0;l++;}}return ans;}static int[] selectionSorting(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {if (arr[min] < arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}return arr;}}
C++
#include <bits/stdc++.h>using namespace std;int main(){long long int n = 5, k = 3;long long int arr[n] = {1, 3, 5, 7, 9};sort(arr, arr + n, greater<long long int>());long long int ans = 0;long long int l = 0;for (long long int i = 0; i < min(k, n); i++){ans = (ans + (1 + l) * arr[i]);}l++;int cnt = 0;for (long long int i = k; i < n; i++){ans = (ans + (1 + l) * arr[i]);cnt++;if (cnt == k){cnt = 0;l++;}}cout << ans << "\n";return 0;}
No comments:
Post a Comment