-
Notifications
You must be signed in to change notification settings - Fork 1
/
Product array puzzle.cpp
72 lines (54 loc) · 1.34 KB
/
Product array puzzle.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
66
67
68
69
70
71
72
//{ Driver Code Starts
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
// nums: given vector
// return the Product vector P that hold product except self at each index
vector<long long int> productExceptSelf(vector<long long int>& nums, int n) {
//code here
long long int l[n];
long long int r[n];
l[0]=1;
r[n-1]=1;
for(int i=1;i<n;i++){
l[i]=l[i-1]*nums[i-1];
}
for(int i=n-2;i>=0;i--){
r[i]=r[i+1]*nums[i+1];
}
vector<long long int> v(n);
for(int i=0;i<n;i++){
v[i]=r[i]*l[i];
}
return v;
}
};
//{ Driver Code Starts.
int main()
{
int t; // number of test cases
cin>>t;
while(t--)
{
int n; // size of the array
cin>>n;
vector<long long int> arr(n),vec(n);
for(int i=0;i<n;i++) // input the array
{
cin>>arr[i];
}
Solution obj;
vec = obj.productExceptSelf(arr,n); // function call
for(int i=0;i<n;i++) // print the output
{
cout << vec[i] << " ";
}
cout<<endl;
}
return 0;
}
// } Driver Code Ends