Delete and Earn in C++


Suppose we have an array nums of integers, we can perform some operations on the array. Here in each operation, we pick any nums[i] and delete it to earn nums[i] amount of points. We must delete every element equal to nums[i] - 1 or nums[i] + 1. Initially the point is 0. We have to find the maximum number of points we can earn by applying such operations. So if the input is like [3,4,2], then the output will be 6. So this is because, if we delete 4, we will get 4 points, consequently 3 will also be deleted. Then delete 2 to get 2 points. 6 total points are earned.

To solve this, we will follow these steps −

  • n := size of nums array, define map m, ret := 0, store the frequency of elements in nums into m

  • cnt := 0

  • for each pair it of m

    • x := key of it

    • temp := x * value of it

    • it1 := point to previous of it, and it2 := point to the previous of it1

    • if cnt >= 1 and x – key of it1 > 1, then temp := m[key of it1]

    • otherwise when cnt >= 2, then temp := temp + m[key of it2]

    • a = m[key of it1] if cnt >= 1, otherwise 0

    • m[key of it] := max of temp and a

    • ret := max of ret and temp

    • increase cnt by 1

  • return ret

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int deleteAndEarn(vector<int>& nums) {
      int n = nums.size();
      map <int, int> m;
      int ret = 0;
      for(int i = 0; i < nums.size(); i++){
         m[nums[i]]++;
      }
      int cnt = 0;
      map <int, int> :: iterator it = m.begin();
      while(it != m.end()){
         int x = it->first;
         int temp = x * it->second;
         map <int, int> :: iterator it1 = prev(it);
         map <int, int> :: iterator it2 = prev(it1);
         if(cnt >= 1 && x - it1->first > 1){
            temp += m[it1->first];
         }
         else if(cnt >= 2){
            temp += m[it2->first];
         }
         m[it->first] = max(temp, cnt >= 1 ? m[it1->first] : 0);
         ret = max(ret, temp);
         it++;
         cnt++;
      }
      return ret;
   }
};
main(){
   vector<int> v = {3,4,2};
   Solution ob;
   cout << (ob.deleteAndEarn(v));
}

Input

[3,4,2]

Output

6

Updated on: 02-May-2020

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements