Day 7 Solution

Hi there and welcome back,

I know that this might be your current state…

But there are a few things I want you to remember….

  • The current job market is VERY, VERY competitive you need to sharpen your skills!

  • The better interviewer gets the job, not the smartest person

  • Interviewing is a skill, the more you practice, the better you become

Now let’s get back to the problem….

You are given an array and an integer.

In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

Return the maximum number of operations you can perform on the array.

Let’s analyze some keywords in this problem…

It’s looking for the number of pairs and the indices are not important there we can … sort!

The first step is to sort the array and then apply the two-pointer pattern.

Once sorted we can apply the two-pointer technique.

Initialize your Left and Right pointers:

L=0

R= arr.size()

Pairs=0

  • If (arr[L] + arr[R]) < K, move the Left pointer one step to the right.

  • If (arr[L] + arr[R]) > K, move the Right pointer one step to the left.

  • If (arr[L] + arr[R]) == K, move both pointers, increment the number of pairs

Lets's look at an example…

Day 7

Here is the complete solution…

Problem: Maximum Operations to Make Array Sum Equal to K

Problem: Maximum Operations to Make Array Sum Equal to K

        
            #include <iostream>
            #include <vector>
            #include <algorithm>

            class Solution {
            public:
                int maxOperations(vector<int>& nums, int k) {
                    int pairs = 0;
                    int L = 0;
                    int R = nums.size() - 1;
                    sort(nums.begin(), nums.end());
                    while (L < R) {
                        if (nums[L] + nums[R] == k) {
                            L++;
                            R--;
                            pairs++;
                        }
                        else if (nums[L] + nums[R] < k) {
                            L++;
                        }
                        else {
                            R--;
                        }
                    }
                    return pairs;
                }
            };
        
    

What would the time complexity of this solution be?

Day 7 Time Complexity

Remember we sorted the array

Login or Subscribe to participate in polls.

Let’s keep it going,

Denisse

Reply

or to participate.