- 列表中的数值有一个规律,数值大小类似谷峰,例如nums = [1, 3, 5, 4, 2, 8, 10, 9, 7, 6],计算其中5-1,5-2,10-2,10-6类似谷峰只是减去相邻两侧的谷底,并返回最大值。
def find_peak_trough_differences(nums):
if len(nums) < 3:
return []
differences = []
for i in range(1, len(nums) - 1):
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
left_trough = nums[i - 1]
for j in range(i - 1, -1, -1):
if j != 0:
if nums[j] < nums[j + 1] and nums[j] < nums[j - 1]:
left_trough = nums[j]
break
elif nums[j] == nums[j - 1]:
left_trough = nums[j]
break
else:
left_trough = nums[0]
right_trough = nums[i + 1]
for k in range(i+1, len(nums)):
if k!=len(nums)-1:
if nums[k] <= nums[k - 1] and nums[k]<= nums[k+1]:
right_trough = nums[k]
break
elif nums[k] == nums[k + 1]:
right_trough = nums[k]
break
else:
right_trough = nums[-1]
differences.append(nums[i] - left_trough)
differences.append(nums[i] - right_trough)
return differences
print(find_peak_trough_differences(x_mid))
nums = [13,7,6,5,8,9,12,6,7,8,0,2,1]
print(max(find_peak_trough_differences(nums)))