Problem D
Tehtävä
Swipe to start coding
Given an integer array nums
of possible sides lengths. Return the largest perimeter of the triangle that can be reached by combining these lengths. If there is no such a perimeter, return 0.
Example 1
Input: nums
= [6, 3, 2, 3, 1, 9, 7]
Output: 22. Use lengths 6, 7 and 9.
Example 2
Input: nums = [4, 1, 5, 9]
Output: 0. There is no possible triangle, you can't use 4, 5, and 9, for example.
Example 3
Input: nums = [7, 15, 7, 7, 6]
Output: 21. Use 7, 7, 7.
Ratkaisu
def largestPerimeter(arr):
for i in range(len(arr)-1):
ind = i
for j in range(i+1, len(arr)):
if arr[ind] > arr[j]:
ind = j
arr[i], arr[ind] = arr[ind], arr[i]
for i in range(len(arr)-3, -1, -1):
if arr[i] + arr[i+1] > arr[i+2]:
return arr[i] + arr[i+1] + arr[i+2]
return 0
nums1 = [10, 8, 12, 17, 27, 11]
nums2 = [10, 7, 1, 1, 2, 1]
nums3 = [10, 7, 20, 1, 2, 1]
print(largestPerimeter(nums1))
print(largestPerimeter(nums2))
print(largestPerimeter(nums3))
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 3. Luku 4
def largestPerimeter(nums):
nums1 = [10, 8, 12, 17, 27, 11]
nums2 = [10, 7, 1, 1, 2, 1]
nums3 = [10, 7, 20, 1, 2, 1]