मान लीजिए हमारे पास nums नामक संख्याओं की एक सूची है। हमें सबसे लंबे सबलिस्ट की लंबाई ढूंढनी है जैसे कि (न्यूनतम लंबाई 3) इसके मान सख्ती से बढ़ रहे हैं और फिर घट रहे हैं।
उदाहरण के लिए, यदि इनपुट nums = [7, 1, 3, 5, 2, 0] है, तो आउटपुट 5 होगा, क्योंकि सबलिस्ट [1, 3, 5, 2, 0] सख्ती से बढ़ती फिर घटती है।
समाधान दृष्टिकोण
इसे हल करने के लिए हम निम्नलिखित चरणों का पालन करेंगे:
i := 0, n := len(a), res := -infinity- जब तक
i < n-2:st := ilinc := 0, ldec := 0- जब तक
i < n-1औरa[i] < a[i+1]:linc += 1, i += 1
- जब तक
i < n-1औरa[i] > a[i+1]:ldec += 1, i += 1
- यदि
linc > 0औरldec > 0:res := max(res, i-st+1)
- जब तक
i < n-1औरa[i] == a[i+1]:i += 1
resलौटाएं यदिres >= 0अन्यथा0
उदाहरण कोड
class Solution:
def solve(self, a):
i, n, res = 0, len(a), float("-inf")
while i < n - 2:
st = i
linc, ldec = 0, 0
while i < n - 1 and a[i] < a[i+1]:
linc += 1
i += 1
while i < n - 1 and a[i] > a[i+1]:
ldec += 1
i += 1
if linc > 0 and ldec > 0:
res = max(res, i - st + 1)
while i < n - 1 and a[i] == a[i+1]:
i += 1
return res if res >= 0 else 0
ob = Solution()
nums = [8, 2, 4, 6, 3, 1]
print(ob.solve(nums))इनपुट
[8, 2, 4, 6, 3, 1]
आउटपुट
5