Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Data Structures
  • Array
  • String
  • Linked List
  • Stack
  • Queue
  • Tree
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Graph
  • Trie
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • AVL Tree
  • Red-Black Tree
  • Advanced Data Structures
Open In App
Next Article:
Minimum sum by choosing minimum of pairs from array
Next article icon

Minimize Cost by selecting Distinct values from Array A

Last Updated : 04 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A and cost array B of size N. The task is to determine the minimum cost(given in array B) by choosing all distinct values from array A.

Note: A[i] will cost us B[i]

Examples:

Input: N = 2, A[] = {16, 16}, B[] = {1, 2}
Output: 1
Explanation: Choosing 16 at the first index will be optimal.

Input: N = 3, A[] = {3, 4, 3}, B[] = {3, 2, 1}
Output: 3

Approach: To solve the problem follow the below idea:

Using map data structure, store the elements in A as key, and if we encounter less value in B for the same element, Update it.

Below are the steps involved:

  • Declare a map data structure m.
    • The key for the map will be valued in A and the value for the map will be cost in B.
  • If we encounter the same key in array A:
    • Update the corresponding value to minimum of value already existing or current cost.
  • Initialize a sum variable.
  • Iterate in map:
    • Sum will be incremented by values of map
  • Return sum.

Below is the implementation of the code:

C++
#include <bits/stdc++.h> #include <iostream> using namespace std;  // Function to find minimum sum int solve(int A[], int B[], int N) {     // Map declaration     unordered_map<int, int> m;      int i = 0;     while (i < N) {         if (m.find(A[i]) != m.end()) {             // Update if value is present             if (m[A[i]] > B[i]) {                 m[A[i]] = B[i];             }         }         else {             m[A[i]] = B[i];         }         i++;     }     int sum = 0;     for (auto a : m) {         sum += a.second;     }      return sum; }  // Driver code int main() {      int N = 4;     int A[] = { 3, 16, 3, 4 };     int B[] = { 3, 9, 1, 1 };      // Function call     cout << solve(A, B, N);     return 0; } 
Java
import java.util.HashMap;  public class MinimumSum {      // Function to find minimum sum     static int solve(int[] A, int[] B, int N) {         // Map declaration         HashMap<Integer, Integer> map = new HashMap<>();          int i = 0;         while (i < N) {             if (map.containsKey(A[i])) {                 // Update if value is present                 if (map.get(A[i]) > B[i]) {                     map.put(A[i], B[i]);                 }             } else {                 map.put(A[i], B[i]);             }             i++;         }                  int sum = 0;         // Calculating the sum of minimum values         for (int value : map.values()) {             sum += value;         }          return sum;     }      // Driver code     public static void main(String[] args) {          int N = 4;         int[] A = { 3, 16, 3, 4 };         int[] B = { 3, 9, 1, 1 };          // Function call         System.out.println(solve(A, B, N));     } } 
Python3
# Function to find minimum sum def solve(A, B, N):     # Dictionary declaration     m = {}      i = 0     while i < N:         if A[i] in m:             # Update if value is present             if m[A[i]] > B[i]:                 m[A[i]] = B[i]         else:             m[A[i]] = B[i]         i += 1      sum_value = 0     for key, value in m.items():         sum_value += value      return sum_value  # Driver code if __name__ == "__main__":     N = 4     A = [3, 16, 3, 4]     B = [3, 9, 1, 1]      # Function call     print(solve(A, B, N)) 
C#
using System; using System.Collections.Generic;  public class Program {     // Function to find minimum sum     public static int Solve(int[] A, int[] B, int N)     {         // Dictionary declaration         Dictionary<int, int> m = new Dictionary<int, int>();          int i = 0;         while (i < N)         {             if (m.ContainsKey(A[i]))             {                 // Update if value is present                 if (m[A[i]] > B[i])                 {                     m[A[i]] = B[i];                 }             }             else             {                 m[A[i]] = B[i];             }             i++;         }         int sum = 0;         foreach (var a in m)         {             sum += a.Value;         }          return sum;     }      // Driver code     public static void Main(string[] args)     {         int N = 4;         int[] A = { 3, 16, 3, 4 };         int[] B = { 3, 9, 1, 1 };          // Function call         Console.WriteLine(Solve(A, B, N));     } } 
JavaScript
function GFG(A, B, N) {     // Create an object (dictionary) to store the minimum values for      // each unique element in A     const m = {};     for (let i = 0; i < N; i++) {         if (m[A[i]] !== undefined) {             // Update if the value is present and is greater than              // the current B value             if (m[A[i]] > B[i]) {                 m[A[i]] = B[i];             }         } else {             // Set the value if not present             m[A[i]] = B[i];         }     }     // Calculate the sum of minimum values     let sumValue = 0;     for (const key in m) {         if (m.hasOwnProperty(key)) {             sumValue += m[key];         }     }     return sumValue; } // Driver Code const N = 4; const A = [3, 16, 3, 4]; const B = [3, 9, 1, 1]; // Function call console.log(GFG(A, B, N)); 

Output
11

Time Complexity: O(N)
Auxiliary space: O(N)


Next Article
Minimum sum by choosing minimum of pairs from array

S

suru21
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Map
  • Arrays
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Map

Similar Reads

  • Minimize sum of distinct elements of all prefixes by rearranging Array
    Given an array arr[] with size N, the task is to find the minimum possible sum of distinct elements over all the prefixes of the array that can be obtained by rearranging the elements of the array. Examples: Input: arr[] = {3, 3, 2, 2, 3}, N = 5Output: 7Explanation: The permutation arr[] = {3, 3, 3,
    8 min read
  • Minimize operations to make both arrays equal by decrementing a value from either or both
    Given two arrays A[] and B[] having N integers, the task is to find the minimum operations required to make all the elements of both the array equal where at each operation, the following can be done: Decrement the value of A[i] by 1 where i lies in the range [0, N).Decrement the value of B[i] by 1
    8 min read
  • Maximize count of distinct elements possible in an Array from the given operation
    Given an array A[] of size N, the task is to maximize the count of distinct elements in the array by inserting the absolute differences of the existing array elements. Examples: Input: A[] = {1, 2, 3, 5} Output: 5 Explanation: Possible absolute differences among the array elements are: (2 - 1) = 1 (
    6 min read
  • Minimum sum by choosing minimum of pairs from array
    Given an array A[] of n-elements. We need to select two adjacent elements and delete the larger of them and store smaller of them to another array say B[]. We need to perform this operation till array A[] contains only single element. Finally, we have to construct the array B[] in such a way that to
    4 min read
  • Minimize cost to make given Array a permutation of 1 to N by given replacements
    Given two arrays a[] and b[] of length N and an integer K (1 ≤ K ≤ N). All the integers in array a[] lie within the range [1, K]. ith value in array b[] denotes the cost of replacing a[i] with any number in the range [1, N]. The task is to find the minimum cost to replace the elements of array a[] t
    6 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Maximize the cost of reducing array elements
    Given an array arr[] of N positive integers. We can choose any one index(say K) of the array and reduce all the elements of the array from index 0 to K - 1 by 1. The cost of this operation is K. If at any index(say idx) element is reduced to 0 then we can't perform this operation in the range [idx,
    6 min read
  • Minimize the cost to make all the adjacent elements distinct in an Array
    Given two integer arrays arr[] and cost[] of size N, the task is to make all adjacent elements distinct at minimum cost. cost[i] denotes the cost to increment ith element by 1.Examples: Input: arr[] = {2, 2, 3}, cost[] = {4, 1, 5} Output: 2 Explanation: The second element has minimum increment cost.
    9 min read
  • Maximize distinct elements of Array by combining two elements or splitting an element
    Given an array arr[] of length N, the task is to maximize the number of distinct elements in the array by performing either of the following operations, any number of times: For an index i(0 ≤ i < N), replace arr[i] with a and b such that arr[i] = a + b.For two indices i (0 ≤ i < N) and n (0 ≤
    9 min read
  • Maximize the count of distinct elements in Array after at most K changes
    Given an array arr[], the task is to find the maximum number of distinct numbers in arr after at most K changes. In each change pick any element X from arr and change it to Y such that L <= Y <= R. Examples: Input: arr[] = {1, 2, 1, 4, 6, 4, 4}, L = 1, R = 5 and K = 2Output: 6Explanation: Foll
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences