0

I have a 2d-array with positive integers (limited to max. of 10^6). The array has a size of 10^5x2 like this:

140173 471588 291471 516770 273559 538464 125329 159490 5034   59284  438681 467752 578846 ...
80182  120937 410438 338171 169200 123061 175433 159358 462440 260476 179648 395141 508690 ...

Now, I need to find the biggest pair of values from the Array, with pairs formed by using one Value of the top row and one from the bottom row. I have a working python example, but it is really slow (attached below). How can I make this faster, or even better, is there a better way?

def solve(n, a, b):

    gD = int(0)

    for i in range(n):
        for j in range(n):
            d = (a[i] + b[j])
            if d > gD: gD = d

    return gD

n is the length of the two arrays, they're of equal length. I loop over every possible value, and if it is bigger than the prev. biggest pair, I save it in gD

3
  • 1
    Why are you not just adding the maximum value from the top row to the maximum value from the bottom row? Commented Sep 27, 2020 at 9:19
  • is a pair made of the values on the same column ? Or can it be, for example, value of 1st row column 5 and value of 2nd row column 10 ? Commented Sep 27, 2020 at 9:36
  • @timgeb I am fairly new to python and didn't know this existed, but I also need the index of the max value Commented Sep 27, 2020 at 10:34

3 Answers 3

1

Maybe just use max?:

list1 = [44545,8876,4571]
list2 = [46321,8468,77798]

print(max(list1)+max(list2))
#122343

to return the first occurrence (there can be multiple elements of same value) of max value:

id = list1.index(max(list1)) #0
id2 = list2.index(max(list2)) #2
Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to get the index of the max value with this?
@jesseb0rn I have edited the code to get ids of first or second list
@Ruli Thank you for the quick answer! Helped a lot!
0

Try this:

max(i+j for i in a for j in b)

Comments

0

Using max seems like the easiest solution.

To mimic your own "solve" function, you could use something like:

def solve(n, a, b):
    assert len(a) == n and len(b) == n
    return max(a) + max(b)

But I wonder if passing n is worth it. If that is not a requirement, you would get:

def solve(a, b):
    assert len(a) == len(b)
    return max(a) + max(b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.