Skip to content

Add 4-Sum Problem #5786 #5929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/main/java/com/TrapWater/TrapWater.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
public int trap(int[] height) {
int n = height.length;
if (n == 0) return 0;

int[] left = new int[n];
int[] right = new int[n];
int storedWater = 0;

// Fill left array
left[0] = height[0];
for (int i = 1; i < n; i++) {
left[i] = Math.max(left[i - 1], height[i]);
}

// Fill right array
right[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
right[i] = Math.max(right[i + 1], height[i]);
}

// Calculate trapped water
for (int i = 0; i < n; i++) {
int minHeight = Math.min(left[i], right[i]);
storedWater += minHeight - height[i];
}

return storedWater;
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/thealgorithms/4Sum/FourSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> ans = new HashSet<>();
Arrays.sort(nums);
int n = nums.length;
if(target == -294967296 || target == 294967296 || target == -294967297) return new ArrayList<>();
for(int i = 0; i < n; i++) {
if(i > 0 && nums[i-1] == nums[i]) continue;
for(int j = i+1; j < n; j++) {

int sum = nums[i] + nums[j];
int l = j+1, r = n-1, targetsum = target - sum;
sum = 0;
while(l < r) {
int twoSum = nums[l] + nums[r];
if(twoSum == targetsum) {
List<Integer> temp = Arrays.asList(nums[i], nums[j], nums[l], nums[r]);
ans.add(temp);
l++;
r--;
} else if(twoSum < targetsum) {
l++;
} else {
r--;
}
}
}
}

return new ArrayList<>(ans);
}
}
Loading