day 16: 238-product-of-array-except-self

This commit is contained in:
Kaushik Narayan R 2023-10-15 09:49:43 -07:00
parent 3de8ed3745
commit b634dfae36
3 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> nums{1, 2, 3, 4};
vector<int> answer{24, 12, 8, 6};
Solution soln;
cout << "Found products correctly? " << soln.test(nums, answer) << endl;
return 0;
}

View File

@ -0,0 +1,35 @@
#include "soln.hpp"
vector<int> Solution::productExceptSelf(vector<int> &nums)
{
int n = nums.size();
vector<int> pres(n);
vector<int> sufs(n);
vector<int> result(n);
// calculate prefixes starting from second
int cur = 1;
for (int i = 1; i < n; i++)
{
pres[i] = cur * nums[i - 1];
cur = pres[i];
}
// calculate suffixes starting from second last
cur = 1;
for (int j = n - 2; j >= 0; j--)
{
sufs[j] = cur * nums[j + 1];
cur = sufs[j];
}
result[0] = sufs[0];
result[n - 1] = pres[n - 1];
for (int i = 1; i < n - 1; i++)
{
result[i] = pres[i] * sufs[i];
}
return result;
}
bool Solution::test(vector<int>& nums, vector<int>& answer) {
return productExceptSelf(nums) == answer;
}

View File

@ -0,0 +1,7 @@
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums);
bool test(vector<int>& nums, vector<int>& answer);
};