diff --git a/leetcode/801-900/0845.Longest-Mountain-in-Array/README.md b/leetcode/801-900/0845.Longest-Mountain-in-Array/README.md index f660ee585..0febd07f0 100644 --- a/leetcode/801-900/0845.Longest-Mountain-in-Array/README.md +++ b/leetcode/801-900/0845.Longest-Mountain-in-Array/README.md @@ -1,28 +1,31 @@ # [845.Longest Mountain in Array][title] -> [!WARNING|style:flat] -> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm) - ## Description +You may recall that an array `arr` is a **mountain array** if and only if: + +- `arr.length >= 3` +- There exists some index `i` **(0-indexed)** with `0 < i < arr.length - 1` such that: + + - `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + - `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + +Given an integer array `arr`, return the length of the longest subarray, which is a mountain. Return `0` if there is no mountain subarray. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: arr = [2,1,4,7,3,2,5] +Output: 5 +Explanation: The largest mountain is [1,4,7,3,2] which has length 5. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Longest Mountain in Array -```go ``` - +Input: arr = [2,2,2] +Output: 0 +Explanation: There is no mountain. +``` ## 结语 diff --git a/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution.go b/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution.go index d115ccf5e..9d50bbcd1 100644 --- a/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution.go +++ b/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution.go @@ -1,5 +1,27 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(arr []int) int { + left := make([]int, len(arr)) + left[0] = 0 + for i := 1; i < len(arr); i++ { + if arr[i] > arr[i-1] { + left[i] = left[i-1] + 1 + } + } + ans := 0 + cnt := 0 + for i := len(arr) - 2; i > 0; i-- { + if arr[i] > arr[i+1] { + cnt++ + } else { + cnt = 0 + } + if left[i] != 0 && cnt != 0 { + ans = max(ans, left[i]+cnt) + } + } + if ans > 0 { + ans++ + } + return ans } diff --git a/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution_test.go b/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution_test.go index 14ff50eb4..13ad401f9 100644 --- a/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution_test.go +++ b/leetcode/801-900/0845.Longest-Mountain-in-Array/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{2, 1, 4, 7, 3, 2, 5}, 5}, + {"TestCase2", []int{2, 2, 2}, 0}, } // 开始测试 @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }