As we all know, Mratyunjay loves candies. He went to a candy shop where n candies were available. Cost of candy with index i is ai .
Strangely, some candies have a negative price (as the owner wants to get rid of old candies), which means the shopkeeper will give him ai rupees for that candy. We know Mratyunjay wants them all, but unfortunately he can carry atmost m candies.
As you're his friend, help Mratyunjay to maximize the money he can earn from buying those candies.
Example:
Input: n = 5, m = 3, a = [-6, 0, 35, -2, 4]
Output: 8
Approach
C++
#include <bits/stdc++.h>using namespace std;int candies(int n, int m, int a[]){sort(a, a + n);int sum = 0;for (int i = 0; i < m; i++){if (a[i] <= 0)sum += abs(a[i]);}return sum;}int main(){int n = 5, m = 3;int a[n] = {-6, 0, 35, -2, 4};cout << candies(n, m, a) << "\n";return 0;}
No comments:
Post a Comment