You are given an integer array A
. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, …) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, …) jumps in the series are called even numbered jumps.
You may from index i
jump forward to index j
(with i < j
) in the following way:
- During odd numbered jumps (ie. jumps 1, 3, 5, …), you jump to the index j such that
A[i] <= A[j]
andA[j]
is the smallest possible value. If there are multiple such indexesj
, you can only jump to the smallest such indexj
. - During even numbered jumps (ie. jumps 2, 4, 6, …), you jump to the index j such that
A[i] >= A[j]
andA[j]
is the largest possible value. If there are multiple such indexesj
, you can only jump to the smallest such indexj
. - (It may be the case that for some index
i,
there are no legal jumps.)
A starting index is good if, starting from that index, you can reach the end of the array (index A.length - 1
) by jumping some number of times (possibly 0 or more than once.)
Return the number of good starting indexes.
Example 1:
Input: [10,13,12,14,15]
Output: 2
Example 2:
Input: [2,3,1,1,4]
Output: 3
Example 3:
Input: [5,1,3,4,2]
Output: 3
Note:
1 <= A.length <= 20000
0 <= A[i] < 100000
Solution: Binary Search + DP
Time complexity: O(nlogn)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution { public: int oddEvenJumps(vector<int>& A) { const int n = A.size(); map<int, int> m; vector<vector<int>> dp(n + 1, vector<int>(2)); dp[n - 1][0] = dp[n - 1][1] = 1; m[A[n - 1]] = n - 1; int ans = 1; for (int i = n - 2; i >= 0; --i) { auto o = m.lower_bound(A[i]); if (o != m.end()) dp[i][0] = dp[o->second][1]; auto e = m.upper_bound(A[i]); if (e != m.begin()) dp[i][1] = dp[prev(e)->second][0]; if (dp[i][0]) ++ans; m[A[i]] = i; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment