| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ProductOfTheLastKNumbers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ProductOfTheLastKNumbersPrefixSum : IProductOfTheLastKNumbers |
| | 16 | | { |
| 1 | 17 | | private readonly List<int> _products = []; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(1) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="num"></param> |
| | 24 | | public void Add(int num) |
| 6 | 25 | | { |
| 6 | 26 | | if (num == 0) |
| 1 | 27 | | { |
| 1 | 28 | | _products.Clear(); |
| 1 | 29 | | } |
| | 30 | | else |
| 5 | 31 | | { |
| 5 | 32 | | if (_products.Count == 0) |
| 2 | 33 | | { |
| 2 | 34 | | _products.Add(num); |
| 2 | 35 | | } |
| | 36 | | else |
| 3 | 37 | | { |
| 3 | 38 | | _products.Add(_products[^1] * num); |
| 3 | 39 | | } |
| 5 | 40 | | } |
| 6 | 41 | | } |
| | 42 | |
|
| | 43 | | /// <summary> |
| | 44 | | /// Time complexity - O(1) |
| | 45 | | /// Space complexity - O(1) |
| | 46 | | /// </summary> |
| | 47 | | /// <param name="k"></param> |
| | 48 | | /// <returns></returns> |
| | 49 | | public int GetProduct(int k) |
| 4 | 50 | | { |
| 4 | 51 | | if (k > _products.Count) |
| 1 | 52 | | { |
| 1 | 53 | | return 0; |
| | 54 | | } |
| | 55 | |
|
| 3 | 56 | | if (k == _products.Count) |
| 1 | 57 | | { |
| 1 | 58 | | return _products[^1]; |
| | 59 | | } |
| | 60 | |
|
| 2 | 61 | | return _products[^1] / _products[_products.Count - k - 1]; |
| 4 | 62 | | } |
| | 63 | | } |