You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<h3 id="solution-1-brute-force-enumeration">Solution 1: Brute Force Enumeration</h3>
86165
+
<p>We first store all edges in the adjacency matrix <span class="arithmatex">\(\textit{g}\)</span>, and then store the degree of each node in the array <span class="arithmatex">\(\textit{deg}\)</span>. Initialize the answer <span class="arithmatex">\(\textit{ans} = +\infty\)</span>.</p>
86166
+
<p>Then enumerate all triplets <span class="arithmatex">\((i, j, k)\)</span>, where <span class="arithmatex">\(i \lt j \lt k\)</span>. If <span class="arithmatex">\(\textit{g}[i][j] = \textit{g}[j][k] = \textit{g}[i][k] = 1\)</span>, it means these three nodes form a connected trio. In this case, update the answer to <span class="arithmatex">\(\textit{ans} = \min(\textit{ans}, \textit{deg}[i] + \textit{deg}[j] + \textit{deg}[k] - 6)\)</span>.</p>
86167
+
<p>After enumerating all triplets, if the answer is still <span class="arithmatex">\(+\infty\)</span>, it means there is no connected trio in the graph, return <span class="arithmatex">\(-1\)</span>. Otherwise, return the answer.</p>
86168
+
<p>The time complexity is <span class="arithmatex">\(O(n^3)\)</span>, and the space complexity is <span class="arithmatex">\(O(n^2)\)</span>. Here, <span class="arithmatex">\(n\)</span> is the number of nodes.</p>
<h3 id="solution-1-reverse-traversal-to-find-the-maximum-on-the-right">Solution 1: Reverse Traversal to Find the Maximum on the Right</h3>
86176
+
<p>We traverse the array <span class="arithmatex">\(\textit{height}\)</span> in reverse order for each element <span class="arithmatex">\(v\)</span>, comparing <span class="arithmatex">\(v\)</span> with the maximum element <span class="arithmatex">\(mx\)</span> on the right. If <span class="arithmatex">\(mx \lt v\)</span>, it means all elements to the right are smaller than the current element, so the current position can see the ocean and is added to the result array <span class="arithmatex">\(\textit{ans}\)</span>. Then we update <span class="arithmatex">\(mx\)</span> to <span class="arithmatex">\(v\)</span>.</p>
86177
+
<p>After the traversal, return <span class="arithmatex">\(\textit{ans}\)</span> in reverse order.</p>
86178
+
<p>The time complexity is <span class="arithmatex">\(O(n)\)</span>, where <span class="arithmatex">\(n\)</span> is the length of the array. Ignoring the space consumption of the answer array, the space complexity is <span class="arithmatex">\(O(1)\)</span>.</p>
0 commit comments