-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max_Sum_Path_In_Two_Sub_Arrays.cpp
65 lines (60 loc) · 1.5 KB
/
Max_Sum_Path_In_Two_Sub_Arrays.cpp
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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int maxPathSum(vector<int> &arr1, vector<int> &arr2) {
int i = 0;
int j = 0;
int n = arr1.size();
int m = arr2.size();
int sum1 = 0;
int sum2 = 0;
int ans = 0;
while(i < n && j < m)
{
if(arr1[i] < arr2[j]) sum1 += arr1[i++];
else if(arr1[i] > arr2[j]) sum2 += arr2[j++];
else
{
ans += max(sum1, sum2) + arr2[j];
sum1 = 0, sum2 = 0;
i++, j++;
}
}
while(i < n) sum1 += arr1[i++];
while(j < m) sum2 += arr2[j++];
ans += max(sum1, sum2);
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr1;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr1.push_back(number);
}
vector<int> arr2;
string input2;
getline(cin, input2);
stringstream ss2(input2);
int number2;
while (ss2 >> number2) {
arr2.push_back(number2);
}
Solution ob;
long long ans = ob.maxPathSum(arr1, arr2);
cout << ans << endl;
}
return 0;
}
// } Driver Code Ends