Arrays - Solution
Arrays - Solution
NOTE - Only functions will be given in the code. Please complete the entire code by writing
themain function & class on your own.
/* You should have a basic knowledge about Java HashSets before following Approach 2. It
willbe taught to you in later chapters. */
return false;
}
Question 2 (DSA Sheet #6)
return left;
}
Approach
public int maxProfit(int[] prices) {
int buy = prices[0];
int profit = 0;
return profit;
}
Question 4 (DSA Sheet #11)
/* This problem can be a little difficult for beginners to solve. Please analyze the solution if
youare not able to come up with the code. */
Approach
public int trap(int[] height) {
int n = height.length;
int res = 0, l = 0, r = n - 1;
int rMax = height[r], lMax = height[l];
while (l < r) {
if (lMax < rMax) {
l++;
lMax = Math.max(lMax, height[l]);
res += lMax - height[l];
} else {
r--;
rMax = Math.max(rMax, height[r]);
res += rMax - height[r];
}
}
return res;
}
Approach
Let us try to understand the problem statement. The first part of the problem statement is
clear, we are asked to find out all the triplets in the given array whose sum is equal to zero. A
triplet is nothing but a set of three numbers in the given array. For example, if nums=[1,2, 3,4]
is the given array, [1,2,3]
[2,3,4] [1,3,4] etc are its triplets.
The last condition that we need to consider is that we cannot have duplicate triplets in our final
result. Example if [-2,-2,0,2] is the given array, we can only consider one of [-2,0,2] from indexes 0, 2,
3 and [- 2,0,2] from indexes 1, 2, 3 in our final result.
BRUTE FORCE -The simple solution to this problem is to find every possible triplet from the
given array, see if its sum is equal to zero and return the result (ensuring there are no
duplicatetriplets in the result).
1. Use three loops to generate all possible triplets for the given array, with each
loop variable keeping track of 1 triplet element each.
2. Next we calculate the sum for each triplet generated in step 1.
3. If the sum is equal to 0 we need to check if it is a unique triplet (not already in our
result set). We can ensure the triplets in our result set are unique by sorting the
triplets and adding it to a hashmap (hashmap overwrites data if the same value
iswritten to the same key multiple times thereby eliminating duplicates).
4. Once we have added all the triplets whose sum is equal to 0 into the
hashmap, we iterate through the hashmap and add it to our result array.
5. Finally we return the result array.
triplet.add(nums[i]);
triplet.add(nums[j]);
triplet.add(nums[k]);
Collections.sort(triplet);
result.add(triplet);
return result;