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!

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

There are significant differences in how C# and C implement and features in object-oriented programming (OOP). 1) The class definition and syntax of C# are more concise and support advanced features such as LINQ. 2) C provides finer granular control, suitable for system programming and high performance needs. Both have their own advantages, and the choice should be based on the specific application scenario.

Converting from XML to C and performing data operations can be achieved through the following steps: 1) parsing XML files using tinyxml2 library, 2) mapping data into C's data structure, 3) using C standard library such as std::vector for data operations. Through these steps, data converted from XML can be processed and manipulated efficiently.

C# uses automatic garbage collection mechanism, while C uses manual memory management. 1. C#'s garbage collector automatically manages memory to reduce the risk of memory leakage, but may lead to performance degradation. 2.C provides flexible memory control, suitable for applications that require fine management, but should be handled with caution to avoid memory leakage.

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C# is suitable for projects that require high development efficiency and cross-platform support, while C is suitable for applications that require high performance and underlying control. 1) C# simplifies development, provides garbage collection and rich class libraries, suitable for enterprise-level applications. 2)C allows direct memory operation, suitable for game development and high-performance computing.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools