![]() |
VOOZH | about |
Given an array A[]. For each element A[i], We need to find the maximum value A[j] (where j ≠ i) that satisfies the condition A[j] ≤ 2*A[i].
If no such value exists for a particular index i, store -1 for that index. Finally, return an array where each position contains the result corresponding to A[i].
Examples:
Input: A[] = [95, 73, 36, 83, 79, 74, 27, 5]
Output: [83, 95, 27, 95, 95, 95,36, -1]
Explanation:
For 95, the largest allowed value is 2 × 95 = 190. The largest number ≤ 190 other than 95 itself is 83.
For 36, the allowed limit is 72. The largest number ≤ 72 is 27, so answer is 27.
For 5, allowed limit is 10, and no element ≤ 10 except itself exists → -1.Input: A[] = [54, 56, 96]
Output: [96, 96, 56]
Explanation:
For 54, allowed limit is 108. The largest number ≤ 108 other than 54 is 96.
For 96, allowed limit is 192. The largest number ≤ 192 other than 96 is 56.
Table of Content
The idea is to process each element A[i] in the array individually and examine all other elements A[j] to find the largest value that satisfies the given conditions. For every element A[i], we first compute a limit as 2 × A[i]. Then, we scan through all elements in the array and consider only those A[j] where the index j ≠ i and the value A[j] ≤ limit. Among all such valid elements, we select the maximum value and store it as the answer for the current index
83 95 27 95 95 95 36 -1
The main idea of this approach is to efficiently find, for each element, the largest value in the array that is at most twice its value. By sorting the array, we know the order of all elements, which allows us to quickly identify suitable candidates without checking every element. However, sorting changes the original indices, so we cannot directly use the sorted positions as answers. To handle this, we always compare the value itself and, if the largest candidate equals the current element, we consider the next smaller element in the sorted array to ensure we select a different element. If no valid element exists, we return -1.
83 95 27 95 95 95 36 -1