算法:算法 - 最長擺動子序列
數字序列被稱爲蠕動序列如果差異 連續數字正和負 之間嚴格交替之間。第一個差異(如果存在的話)可能是正數 或負數。具有少於兩個元素的序列一般是擺動序列。
例如,[1,7,4,9,2,5]是一個擺動序列,因爲 差異(6,-3,5,-7,3)交替爲正數和負數。相比之下,[1,4,7,2,5]和[1,7,4,5,5]不是擺動序列, 首先是因爲它的前兩個差異是正的,而第二個是因爲其最後的差異是零。
給定一個整數序列,返回最長的 子序列的長度,這是一個擺動序列。通過 刪除 原始序列中的一些元素(最終也爲零),從而使其餘元素保持其原始 的順序,從而獲得子序列。
實例:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
我的溶液:
def wiggle_max_length(nums)
[ build_seq(nums, 0, 0, true, -1.0/0.0),
build_seq(nums, 0, 0, false, 1.0/0.0)
].max
end
def build_seq(nums, index, len, wiggle_up, prev)
return len if index >= nums.length
if wiggle_up && nums[index] - prev > 0 || !wiggle_up && nums[index] - prev < 0
build_seq(nums, index + 1, len + 1, !wiggle_up, nums[index])
else
build_seq(nums, index + 1, len, wiggle_up, prev)
end
end
這是工作於較小的輸入(例如[1,1,1,3,2,4,1,6, 3,10,8]和所有樣本輸入,但其失敗的非常大的輸入(這是很難調試),如:
[33,53,12,64,50,41,45 ,21,97,35,47,92,39,0,93,55,40,46,69,42,6,95,51,68,72,9,32,84,34,64,6,2 ,26,98,3,43,30,60,3,68,82,9,97,19,27,98,99,4,30,96,37,9,78,43,64,4,65 ,30,84,90,87,64,18,50,60,1,40,32,48,50,76,100,57,29,63,53,46,57,93,98,42,80,82 ,9,41,55,69,84,82,79,30,79,18,97,67,23,52,38,74,15]
其中應該有輸出:67但我soln輸出57.有人知道這裏有什麼問題嗎?
什麼是預期的時間複雜度? – marvel308
不確定,但不是我關心的atm - 現在我正在尋找準確性 – Sunny
僅供參考:https://en.wikipedia.org/wiki/Longest_alternating_subsequence – Stefan