Reduces an array to at most one element by the given operation
In this problem, we reduce the array size to 1 or 0 by performing the given operation every round.
We can sort the array in each round to get the maximum element in each iteration. In addition, we can also use the head data structure to improve the performance of the code.
Problem Statement - We are given a nums[] array. We need to reduce the array by doing the following.
Select the two largest elements in the array.
If two elements are the same, delete the two elements from the array.
If the two elements are not the same, delete the two elements from the array and insert abs(first − secondary) into the array.
Print the last element of the array. If the array is empty, print 0.
Example
enter
nums = {5, 9, 8, 3, 2, 5};
Output
0
illustrate
In the first round, we take 9 and 8 and add their difference to the array. Therefore, the array becomes [5, 3, 2, 5, 1].
In the second round, we take 5 and 5. Therefore, the array becomes [3, 2, 1].
Next round, we take 3 and 2. Therefore, the array becomes [1, 1]
In the last round, we take 1 and 1. Therefore, the array becomes empty and we print 0.
enter
nums = {5, 5, 5, 5, 5};
Output
5
Explanation- We delete a pair of 5 twice and there is one 5 remaining in the array.
enter
nums = {4, 8, 7, 6};
Output
1
Explanation - First, we select 8 and 7. Therefore, the array becomes [4, 1, 6]. After that, we select 4 and 6. Therefore, the array becomes [1, 2]. On the last operation, the array becomes [1].
method 1
In this method, we will iterate through the array until the size of the array becomes 1 or 0. In each iteration, we will sort the array and perform the given operation on the first 2 elements of the sorted array. Finally, we will print the output based on the array size.
algorithm
Step 1- Store the size of the array in the "len" variable.
Step 2- Start traversing the array using a while loop.
Step 3- Use the sort() method in a loop to sort the array in reverse.
Step 4- Get the first and second elements of the array. Also, calculate the difference between the first and second elements of the array.
Step 5− If the difference is 0, delete the first two elements of the array and reduce 'len' by 2. If the difference is not 0, delete the first 2 elements and decrement 'len' minus 1.
Step 6- Finally, if the size of the array is 0, return 0. Otherwise, the first element of the array is returned.
Example
#include <bits/stdc++.h> using namespace std; int findLast(vector<int> &nums) { int len = nums.size(); int p = 0; while (len > 1) { // Sort array in reverse order sort(nums.begin(), nums.end(), greater<int>()); // Take the first and second elements of the array int a = nums[0]; int b = nums[1]; // Take the difference between the first and second element int diff = a - b; if (diff == 0) { nums.erase(nums.begin()); nums.erase(nums.begin()); len -= 2; } else { nums.erase(nums.begin()); nums.erase(nums.begin()); nums.push_back(diff); len -= 1; } } // When the size of the array is 0 if (nums.size() == 0) return 0; return nums[0]; } int main() { vector<int> nums = {5, 9, 8, 3, 2, 5}; cout << "The last remaining element after performing the given operations is " << findLast(nums) << "\n"; return 0; }
Output
The last remaining element after performing the given operations is 0
Time complexity - O(N*NlogN), where O(N) is used to iterate over the array and O(NlogN) is used to sort the array in each iteration.
Space complexity - O(N) to sort the array.
Method 2
In this approach, we will use a priority queue, which implements the heap data structure. It always stores elements in sorted order. So we can easily remove the first 2 largest elements.
algorithm
Step 1- Define "p_queue" named priority queue.
Step 2- Insert all array elements into the priority queue.
Step 3- Iterate until the size of the priority queue is greater than 1.
Step 4- Delete the first 2 elements of the priority queue one by one.
Step 5- Find the difference between two elements.
Step 6- If the difference is not 0, push it into the priority queue.
Step 7− Finally, if the queue size is 0, return 0.
Step 8 - Otherwise, return the element at the top of the queue.
Example
#include <bits/stdc++.h> using namespace std; int findLast(vector<int> &nums) { // Defining a priority queue priority_queue<int> p_queue; // Inserting array elements in priority queue for (int p = 0; p < nums.size(); ++p) p_queue.push(nums[p]); // Make iterations while (p_queue.size() > 1) { // Take the first element from queue int first = p_queue.top(); p_queue.pop(); // Get the second element from queue int second = p_queue.top(); p_queue.pop(); // Take the difference of first and second elements int diff = first - second; if (diff != 0) p_queue.push(diff); } // When queue is empty if (p_queue.size() == 0) return 0; // Return the last remaining element return p_queue.top(); } int main() { vector<int> nums = {5, 9, 8, 3, 2, 5}; cout << "The last remaining element after performing the given operations is " << findLast(nums) << "\n"; return 0; }
Output
The last remaining element after performing the given operations is 0
Time complexity - The time complexity of inserting and deleting elements in the priority queue is O(NlogN).
Space Complexity - O(N) to store elements in the priority queue.
Priority queue data structure is always useful when we need to arrange the array data in a specific order after inserting or deleting any element. It implements the heap data structure, thereby enabling insertion and deletion.
The above is the detailed content of Reduces an array to at most one element by the given operation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article details C function return types, encompassing basic (int, float, char, etc.), derived (arrays, pointers, structs), and void types. The compiler determines the return type via the function declaration and the return statement, enforcing

Gulc is a high-performance C library prioritizing minimal overhead, aggressive inlining, and compiler optimization. Ideal for performance-critical applications like high-frequency trading and embedded systems, its design emphasizes simplicity, modul

This article explains C function declaration vs. definition, argument passing (by value and by pointer), return values, and common pitfalls like memory leaks and type mismatches. It emphasizes the importance of declarations for modularity and provi

This article details C functions for string case conversion. It explains using toupper() and tolower() from ctype.h, iterating through strings, and handling null terminators. Common pitfalls like forgetting ctype.h and modifying string literals are

This article examines C function return value storage. Small return values are typically stored in registers for speed; larger values may use pointers to memory (stack or heap), impacting lifetime and requiring manual memory management. Directly acc

This article analyzes the multifaceted uses of the adjective "distinct," exploring its grammatical functions, common phrases (e.g., "distinct from," "distinctly different"), and nuanced application in formal vs. informal

This article details efficient STL algorithm usage in C . It emphasizes data structure choice (vectors vs. lists), algorithm complexity analysis (e.g., std::sort vs. std::partial_sort), iterator usage, and parallel execution. Common pitfalls like

This article explains the C Standard Template Library (STL), focusing on its core components: containers, iterators, algorithms, and functors. It details how these interact to enable generic programming, improving code efficiency and readability t
