703405. Minimum sum of two elements from two arrays
Basic
Minimum sum of two elements from two arrays
Summary
Given two arrays, find the minimum sum of two elements, one from each array. This problem requires understanding of basic algorithmic concepts and data structures.
Detailed Explanation
The problem can be solved by iterating through both arrays simultaneously and calculating the sum of each pair. The smallest sum is then returned as the result.
Here's a step-by-step breakdown of the solution:
- Initialize variables
min_sumto store the minimum sum, andsumto calculate the current sum. - Iterate through both arrays using two pointers,
ifor array 1 andjfor array 2. - For each pair of elements, calculate the sum by adding the corresponding elements from both arrays (e.g.,
arr1[i] + arr2[j]). - Compare the current sum with the minimum sum found so far (
min_sum). If the current sum is smaller, updatemin_sum. - Repeat steps 2-4 until all pairs of elements have been considered.
- Return the minimum sum as the result.
Time complexity: O(m * n), where m and n are the sizes of the two arrays.
Space complexity: O(1), as we only use a constant amount of space to store min_sum and intermediate variables.
Optimized Solutions
Java
public class Main {
public static int minSum(int[] arr1, int[] arr2) {
int min_sum = Integer.MAX_VALUE;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
int sum = arr1[i] + arr2[j];
if (sum < min_sum) {
min_sum = sum;
}
}
}
return min_sum;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
System.out.println(minSum(arr1, arr2));
}
}