0
How to delete the longest chain of even elements?
How to delete the longest chain of even elements from the array?
7 Respuestas
+ 10
Sorry, I misunderstood your question.
Well in your case you need to keep track of two things.
1) Longest sequence
2) The index where the longest sequence ends
If you know at what index the longest sequence ends, you can get the starting index of the sequence too by subtracting the length of the sequence with ending index.
Below is the implementation
https://code.sololearn.com/c6ECVVCGnxeX/?ref=app
+ 9
You cannot actually delete an element from the array. What you can do is overwrite it by the next element of the array and put zero/null to the duplicate place.
In simple words you need to shift elements backwards.
+ 9
Try out this code, it removes all even elements from array
#include <iostream>
using namespace std;
int main() {
int size = 100;
int arr[size] = {0};
for(int i = 0; i < size; i++)
arr[i] = i + 1;
cout << "Array having even and odd numbers\n";
for(int i = 0; i < size; i++)
cout << arr[i] << " ";
for(int i = 0; i < size; i++) {
for(int j = 0; j < size - 1; j++) {
if(arr[j] % 2 == 0) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
arr[j+1] = 0;
}
}
}
cout << "\n\nArray having only odd numbers\n";
for(int i = 0; i < size; i++)
cout << arr[i] << " ";
return 0;
}
+ 4
If I understand your question correctly, you have an array of random integers and you want to remove the longest consecutive even elements. cmiiw.
If that's the case, you need to find the beginning of longest chain and the length of that chain. To do that, you need to iterate through the array and check if an element is even. That element will be the beginning of your chain. Then check if the next elements until you encounter an odd element which gives you the length of the chain. You just need to repeat the process and check if the length of the succeeding chains is longer than the first.
Deleting/overwriting the elements of that chain should be the easiest part.
I hope that helps.
+ 4
"How to delete...from the array?"
This is signaling for doing something dynamically like using a linked list. But surely it needs more thought to implement and also taking care of the possible memory leakages.
The best option IMO is using a vector for handling dynamic resizing.
_____
This tutorial is for C but works for C++, as well: http://www.zentut.com/c-tutorial/c-linked-list/#C_Linked_List_Program
https://en.cppreference.com/w/cpp/container/vector
0
I know this, yes. But how can I overwrite the whole chain of even elements and this chain must be the longest of all chains...
0
Thanks, I will try