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
Solutionclass contains theMaxMinArraymethod, which takes the arrayarrand its sizenas input and returns an array containing the minimum and maximum values.Inside the
MaxMinArraymethod, we initialize two variables,minValueandmaxValue, 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 currentminValueand the element at indexiin the array. This way, we keep updating theminValueif we find a smaller element in the array.Similarly, we use the
Math.max()method to find the maximum value between the currentmaxValueand the element at indexiin the array. This way, we keep updating themaxValueif we find a larger element in the array.After the loop, we have obtained the
minValueandmaxValue, 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