W
W
weranda2016-06-10 07:37:03
Python
weranda, 2016-06-10 07:37:03

How to find adjacent array elements whose sum is maximum (minimum)?

Greetings
The first part of the question
is not yet possible to comprehend how to solve the problem correctly:

Given an array. Find two adjacent elements whose sum is maximum.

I tried to solve this problem. It seems to have worked out, but I want to get an understanding of how exactly to solve it correctly, which options will be optimal, and most importantly, why. I got three options, but it seems that there are better solutions.
# первый вариант
lst0 = [random.randrange(1, 10) for x in range(5)]
print(lst0)
max_lst = 0

for x in range(len(lst0) - 1):
   x = lst0[x] + lst0[x + 1]
   if x > max_lst:
      max_lst = x

print(max_lst, end='\n\n\n')


# второй вариант
lst1 = [random.randrange(1, 10) for x in range(5)]
print(lst1)
lst1 = [lst1[x] + lst1[x + 1] for x in range(len(lst1) - 1)]
print(max(lst1), end='\n\n\n')


# третий вариант
lst2 = [random.randrange(1, 10) for x in range(5)]
print(lst2)
lst2 = [lst2[x] + lst2[x + 1] for x in range(len(lst2) - 1)]
lst2.sort()
print(lst2[-1])

Which of these or other options for solving the problem should be chosen and why?
The second part of the question
During the solution, I wanted to get two neighboring elements, the sum of which is minimal, and if, using the example of the second and third options, I understand how to solve the problem of finding the minimum sum of two consecutive elements, then the example of the first option does not. According to the algorithm of the first option, to find the maximum sum of two consecutive elements, I use the comparison if x > max_lst, but what to do in the case of finding the minimum sum, it is not clear to me what to compare with.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2016-06-10
@weranda

The task says to find the elements, not their sum.

A
aRegius, 2016-06-10
@aRegius

Hello.

num = [.........]
opt = list(map(lambda x, y: (x + y, (x, y)), num, num[1:]))
max_sum_pair = max(opt)    # итоговый кортеж МАКСИМУМ (сумма, (число 1, число 2))
min_sum_pair = min(opt)     # МИНИМУМ

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question