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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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



C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.
