Array Easy Problems Solution
Let's start by some basic Easy Arrays problems solve in DSA
1. Maximum and Minimum Element in an Array
Explanation:
The code starts by taking input from the user for the size of the array (
n
) and then the elements of the array (arr
).The
Solution
class contains theMaxMinArray
method, which takes the arrayarr
and its sizen
as input and returns an array containing the minimum and maximum values.Inside the
MaxMinArray
method, we initialize two variables,minValue
andmaxValue
, to the first element of the array (arr[0]
). This is done as we need some initial values to start comparing with the rest of the array elements.We then iterate through the array starting from index 1 (since we have already initialized the variables with the first element).
Inside the loop, we use the
Math.min()
method to find the minimum value between the currentminValue
and the element at indexi
in the array. This way, we keep updating theminValue
if we find a smaller element in the array.Similarly, we use the
Math.max()
method to find the maximum value between the currentmaxValue
and the element at indexi
in the array. This way, we keep updating themaxValue
if we find a larger element in the array.After the loop, we have obtained the
minValue
andmaxValue
, so we return them as a new array using thereturn new int[]{minValue, maxValue};
.
Time Complexity:
- The time complexity of this solution is O(n) because we are iterating through the array once to find the minimum and maximum values.
Space Complexity:
- The space complexity is O(1) because we are using a constant amount of extra space (two integer variables) regardless of the