| | 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.MaximumDistanceInArrays; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumDistanceInArraysGreedy : IMaximumDistanceInArrays |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="arrays"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MaxDistance(IList<IList<int>> arrays) |
| 3 | 24 | | { |
| 3 | 25 | | var maxDistance = 0; |
| | 26 | |
|
| 3 | 27 | | var max = arrays[0][arrays[0].Count - 1]; |
| 3 | 28 | | var min = arrays[0][0]; |
| | 29 | |
|
| 14 | 30 | | for (var i = 1; i < arrays.Count; i++) |
| 4 | 31 | | { |
| 4 | 32 | | var currentMin = arrays[i][0]; |
| 4 | 33 | | var currentMax = arrays[i][^1]; |
| | 34 | |
|
| 4 | 35 | | maxDistance = Math.Max(maxDistance, Math.Abs(currentMax - min)); |
| 4 | 36 | | maxDistance = Math.Max(maxDistance, Math.Abs(max - currentMin)); |
| | 37 | |
|
| 4 | 38 | | min = Math.Min(min, currentMin); |
| 4 | 39 | | max = Math.Max(max, currentMax); |
| 4 | 40 | | } |
| | 41 | |
|
| 3 | 42 | | return maxDistance; |
| 3 | 43 | | } |
| | 44 | | } |