Find the longest even sum in array
The sum of two odd numbers is even and the sum of two even numbers is even, so a subarray has an even sum if and only if there are an even number of odd numbers. Thus, we can find the answer by keeping track of the index of the first odd number, the index of the last odd number, and the number of odd numbers. If there are an even number of odd numbers, the entire array's sum is even. Otherwise, we can get maximum length of the subarray from the index of the first odd number plus one to the end of the array and the subarray from the front of the array to one less than the last index of an odd number. These subarrays are both the largest possible with an even number of odd numbers, since one odd number is excluded from each one.
function longestEven(arr) {
let firstOdd = -1,
lastOdd = -1,
oddCount = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 1) {
if (firstOdd === -1) firstOdd = i;
lastOdd = i;
++oddCount;
}
}
return oddCount % 2 === 0 ? arr.length :
Math.max(arr.length - (firstOdd + 1), lastOdd);
}
console.log(longestEven([2, 3, 1, 8, 4, 7, 2]));
Find the Min Even Integer and Max Even Integer in an Array
This test case exposes one of the dark sides of your code where you have initialized your min
and max
to A[1]
regardless of whether A[1]
is odd or even.
Problem:
There may be cases where the array does not contain any even number. In such cases, you may wish to print so instead of printing -1
or INT_MIN
or INT_MAX
.
If you are new to INT_MIN
and INT_MAX
, this will serve as a starter before proceeding to the solution.
Solution:
This solution modifies your code in such a way that it handles all the cases given that you provide the inputs without any error.
Have a flag to know whether you found your
min
andmax
:int foundAnswer = 0;
Add the header file
limits.h
and initialize yourmin
andmax
as
follows:min = INT_MAX;
max = INT_MIN;Modify your loop such that the flag serves a purpose:
Note:
Don't waste the zeroth index of your array without any reason.
Modify your array declaration and input loop accordingly before
changing this one.for (i = 0; i < ARRAY_SIZE; ++i)
{
if (A[i] % 2 == 0)
{
foundAnswer = 1;
if (A[i] < min) min = A[i];
if (A[i] > max) max = A[i];
}
}Modify your printing code slightly so that all the cases are
covered.if (foundAnswer)
{
// Print min
// Print max
}
else
{
// Print "min and max not found"
}
Bonus:
You can learn from the following links in order to optimize your code:
How do I check if an integer is even or odd using bitwise operators
The algorithms discussed here will provide you with a better time complexity to achieve the same.
How do you find the max even sum from an array with using a number only once?
Appreciate that you will do one of two things with the total sum of all elements in the array. If the total sum be even, you return that number, but if it be odd, then you will have to remove a number in order to make it even. Note that removing an even number will leave the remaining sum odd, so there is no point in removing an even number. But, since the total sum be odd, then there must be at least one odd number in the array.
So all you need to do if the total sum be odd is to iterate over the array and remove the smallest odd number. And there is guaranteed to be at least one odd number.
Here is an implementation:
public int findMaxEvenSum(int[] array) {
int total = 0;
for (int i=0; i < array.length; ++i) {
total += array[i];
}
if (total % 2 == 0) {
return total;
}
// otherwise iterate over the array and remove the smallest odd
// number from the sum
int lastOdd = 0;
for (int i=0; i < array.length; ++i) {
if (array[i] % 2 == 1 && (lastOdd == 0 || array[i] < lastOdd)) {
total += lastOdd;
total -= array[i];
lastOdd = array[i];
}
}
return total;
}
How to find 3 largest even numbers in an array with C?
There are a few problems here:
You should only examine the array entries that are defined. Instead, you are looking at the entire array, including the undefined portion from
nNumbers
throughMAX_NUMBERS-1
. You will likely pick up garbage values there. Change yourfor
loops to:for (i = 0; i < nNumbers; i++)
You are initializing
greatest1
, etc. to the first number in the array. That doesn't work if the number is odd and happens to be large enough to block the even number you're looking for.If one of the largest even numbers occurs more than once, you will ignore the duplicates. For instance, if the largest number is 1000, and it occurs three times, you probably want to add all three and return 3000. You can fix this by keeping track of the indices you have chosen, and only rejecting a duplicate if the index matches, rather than the value.
Find the highest odd number in an array using recursion in java
While replacing the value of high with arr[index] if arr[index] value is higher just check if the value is odd. Else keep the high value as it is. Try the following code. It will return -1 if there have no odd value in the array(assuming all the values of array are positive, if there have possibility of negative value then you can replace -1 with integer min). Let me know if you don't understand any part.
public static int highestOdd(int [] arr, int index) {
if(arr.length - 1 == index) return arr[index] % 2 > 0 ? arr[index] : -1;
int high = highestOdd(arr,index+1);
if(arr[index] % 2 > 0) high = high > arr[index] ? high : arr[index];
return high;
}
Related Topics
Calculating the Angle Between Two Lines Without Having to Calculate the Slope (Java)
Notifydatasetchanged() Makes the List Refresh and Scroll Jumps Back to the Top
How to Use a Regex to Search Backwards Effectively
Maven Clean Issue - Non-Resolvable Import Pom - Could Not Transfer Artifact from Nexus
Remove End of Line Characters from Java String
Getting Versioncode and Versionname from Google Play
How to Persist a Property of Type List<String> in Jpa
How to Run Selenium Webdriver in the Background
How to Check If a Java 8 Stream Is Empty
Java Nullpointerexception When Adding to Arraylist
Rsa Decryption Error - Illegalblocksizeexception: Data Must Not Be Longer Than 128 Bytes
Java8 Way to Handle If..Else Check in Collections
How to Sort by Two Fields in Java and Specify Sort Direction
How to Stop the Items Duplication in Recyclerview Android
Jackson Serializes a Zoneddatetime Wrongly in Spring Boot
How to Pass Json Object as a Pathvariable to Spring Controller
Org.Hibernate.Annotationexception: @Onetoone or @Manytoone on <Entity> References an Unknown Entity