-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay9.cpp
More file actions
45 lines (35 loc) · 1.01 KB
/
Day9.cpp
File metadata and controls
45 lines (35 loc) · 1.01 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
/*
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can't use division?
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> productArray(const vector<int> &arr)
{
int n = arr.size();
vector<int> result(n, 1);
for (int i = 1; i < n; i++)
{
result[i] = result[i - 1] * arr[i - 1];
}
int suffixProduct = 1;
for (int i = n - 2; i >= 0; i--)
{
suffixProduct *= arr[i + 1];
result[i] *= suffixProduct;
}
return result;
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
vector<int> result = productArray(arr);
for (int i : result)
{
cout << i << " ";
}
cout << endl;
return 0;
}