Range Addition II in C++


Suppose we have one m * n matrix called M and this is initialized with all 0's and we also have several update operations. Now, operations are represented by a 2D array, and each operation is represented by an array with two positive integers x and y, it means M[i][j] should be added by one for all values i in range 0 to a - 1 and all values j in range 0 to b - 1. We have to find the count of the number of maximum integer in the matrix after performing all the operations.

So, if the input is like m = 3, n = 3 and operations = [[2,2],[3,3]]., then the output will be 4,

Initially matrix is like

000
000
000

After performing [2,2], we will get

110
110
000

After performing [2,2], we will get

221
221
111

To solve this, we will follow these steps −

  • minR := m, minC := n

  • for op in ops array

    • minR := minimum of minR and op[0]

    • minC := minimum of minC and op[1]

  • return minR * minC

Example 

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

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int maxCount(int m, int n, const vector<vector<int>>& ops) {
      int minR = m;
      int minC = n;
      for (const auto& op : ops){
         minR = min(minR, op[0]);
         minC = min(minC, op[1]);
      }
      return minR * minC;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{2,2},{3,3}};
   cout << (ob.maxCount(3,3,v));
}

Input

3,3,{{2,2},{3,3}}

Output

4

Updated on: 11-Jun-2020

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements