Find last remaining Array element by multiplying boundary elements based on given rules
Given an array arr, the task is to find the only remaining element in the array after applying the below operation till there is only one element left in the array. In an operation, multiply the boundary elements of this array and if the size of the array is:
- Even: Insert the product in the middle of the array and remove the boundary elements
- Odd: Subtract the middle element from the product and replace the middle element with the absolute difference and remove the boundary elements.
Input: arr = [ 1, 2, 3, 4, 5, 6 ]
Explanation: See the image below for explanation.
Input: arr = [ 3, 5, 1, 8, 9]
Approach: The solution is based on greedy approach. Delete the elements from the ends of the array and insert the data in the middle of the array. Now follow the below steps to solve this problem:
- Run a while loop, till the size of the array arr is greater than 1. In each iteration of this loop:
- Take the product of the first and the last elements and then pop them.
- If the size of the array is even, then insert the product in the middle of the array arr.
- If it is odd then subtract the middle element from the product and replace it with the middle element.
- After the loop ends, print the only remaining element in the array.
Time Complexity: O(N2)
Auxiliary Space: O(1)