-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheighth.java
More file actions
92 lines (63 loc) · 1.83 KB
/
Copy patheighth.java
File metadata and controls
92 lines (63 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.*;
public class eighth {
static int[] inputArray(Scanner sc, int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
// Function to find sum of middle elements without creating merged array
static int findMiddleSum(int[] arr1, int[] arr2, int n) {
int i = 0, j = 0;
int count = 0;
int total = 2 * n;
int mid1 = total / 2 - 1;
int mid2 = total / 2;
int firstMiddle = 0;
int secondMiddle = 0;
while (i < n && j < n) {
int current;
if (arr1[i] <= arr2[j]) {
current = arr1[i++];
} else {
current = arr2[j++];
}
if (count == mid1)
firstMiddle = current;
if (count == mid2) {
secondMiddle = current;
break;
}
count++;
}
while (count <= mid2 && i < n) {
if (count == mid1)
firstMiddle = arr1[i];
if (count == mid2) {
secondMiddle = arr1[i];
break;
}
i++;
count++;
}
while (count <= mid2 && j < n) {
if (count == mid1)
firstMiddle = arr2[j];
if (count == mid2) {
secondMiddle = arr2[j];
break;
}
j++;
count++;
}
return firstMiddle + secondMiddle;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr1 = inputArray(sc, n);
int[] arr2 = inputArray(sc, n);
System.out.println(findMiddleSum(arr1, arr2, n));
}
}