From 15bd5cb74391fb372caa7b49e376ff7818206039 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 15 Mar 2024 17:28:55 +0100 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB238.=20Product=20of=20Array?= =?UTF-8?q?=20Except=20Self=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/product-of-array-except-self.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cs/product-of-array-except-self.cs diff --git a/cs/product-of-array-except-self.cs b/cs/product-of-array-except-self.cs new file mode 100644 index 0000000..39fe6cc --- /dev/null +++ b/cs/product-of-array-except-self.cs @@ -0,0 +1,28 @@ +public class Solution { + private int Get(int[] products, int idx) { + if (idx < 0 || idx >= products.Length) { + return 1; + } + return products[idx]; + } + + public int[] ProductExceptSelf(int[] nums) { + var left = new int[nums.Length]; + var right = new int[nums.Length]; + + for (var i = 0; i < nums.Length; ++i) { + left[i] = nums[i] * Get(left, i - 1); + + int j = nums.Length - i - 1; + right[j] = nums[j] * Get(right, j + 1); + } + + var result = new int[nums.Length]; + + for (var i = 0; i < nums.Length; ++i) { + result[i] = Get(left, i - 1) * Get(right, i + 1); + } + + return result; + } +}