| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.Triangle; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class TriangleDynamicProgramming : ITriangle |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^2) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="triangle"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int MinimumTotal(IList<IList<int>> triangle) |
| | 2 | 24 | | { |
| | 2 | 25 | | var rowsCount = triangle.Count; |
| | 2 | 26 | | var cellsCount = rowsCount; |
| | | 27 | | |
| | 10 | 28 | | for (var rowIndex = rowsCount - 1; rowIndex > 0; rowIndex--) |
| | 3 | 29 | | { |
| | 3 | 30 | | var row = triangle[rowIndex]; |
| | 3 | 31 | | var previousRow = triangle[rowIndex - 1]; |
| | | 32 | | |
| | 18 | 33 | | for (var cellIndex = 0; cellIndex < cellsCount - 1; cellIndex++) |
| | 6 | 34 | | { |
| | 6 | 35 | | var value = row[cellIndex]; |
| | 6 | 36 | | var nextValue = row[cellIndex + 1]; |
| | | 37 | | |
| | 6 | 38 | | previousRow[cellIndex] += value < nextValue ? value : nextValue; |
| | 6 | 39 | | } |
| | | 40 | | |
| | 3 | 41 | | cellsCount--; |
| | 3 | 42 | | } |
| | | 43 | | |
| | 2 | 44 | | return triangle[0][0]; |
| | 2 | 45 | | } |
| | | 46 | | } |