• Coursera-Algorithmic-Toolbox
  • assignment solutions
  • 1.2 max pairwise product.py

Anoubhav Agarwaal's avatar

Maximum Pairwise Product

Cloistered Monkey

2018-06-24 16:42

Since the test only uses python standard library I'll try and stick to that, but since the stress-test isn't part of the assignment I'll cheat and use numpy to generate the random input.

Problem Statement

Find the maximum product of two distinct numbers in a sequence of non-negative integers.

  • Input: A sequence of non-negative integers.
  • Output: The maximum value that can be obtained by multiplying two different elements from the sequence.

Given a sequence of non-negative numbers \(a_1,\ldots,a_n\), compute

\[ \max_{1 \le i \neq j \le n} a_i a_j \]

\(i\) and \(j\) should be different, although \(a_i\) and \(a_j\) might be equal.

 
First Line - the number of input values
Second Line \(a_1 \ldots a_n\) - space-separated list of values
the maximum pairwise product from the input.
\(2 \le n \le 2 \times 10^5; 0 \le a_1,\ldots,a_n\le 2 \times 10^5\)

Example Values

First Input Second Input Output
5 5 6 2 7 4 42
3 1 2 3 6
10 7 5 14 2 8 8 10 1 2 3 140
Limit Value
Time 5 seconds
Memory 512 Mb

Some Constants

This is just a translation of some of the problem statement values to python so we can use them.

These are some functions to help validate the algorithms.

Brute Force Implementation

This is given as part of the problem. It traverses all the values and finds the largest product.

Because we are traversing all the numbers twice, the brute-force version has a run time of \(O(n^2)\). Since the \(n\) can be from \(2\) to \(2 \times 10^5\) that means our maximum run time will be \(4 \times 10^10\), which is too large.

Running this through the grader gives this output.

Instead of using nested for-loops, we can search the numbers twice to find the two biggest numbers, this changes the run time to \(2n\) or \(O(n)\).

This one passes the grader, doing surprisingly well, even though I was thinking it would need more optimizing.

Another Improvement

Rather than go through the second loop, I thought that since the previous maximum value is always the next highest value so far, we can just save it directly.

Stress Test

Even thought we're already passing, part of the assignment was to create a stress test to really exercise the algorithm once you have it passing.

Boosted Brute Force

To try and get this working I'm going to use numba to (hopefully) speed it enough to make the stress test runnable.

Since we need the top two values we can get a more efficient algorithm by sorting the values.

Maximum pairwise product →

Sep 2, 2017 • algorithms , C++

Let’s take a quick look at a simple problem:

Given a list of numbers, how would you determine the maximum pairwise product of numbers in the list?

For example, if we have the list [1; 3; 5; -2] the maximum pairwise product is 15 , which is the product of 3 and 5 .

The straigt-forward approach is to compute all possible pairwise products and identify the maximum among the intermediate results:

Since we have two loops that iterate over the list of numbers, the time complexity is O(n 2 ).

Can we do better? Yes, we can. The idea is to find the maximum and the second maximum elements in the list - and their product would be the maximum pairwise product.

Simple and sweet!

Nkwachi's Cave

Solving the maximum pairwise product algorithm.

Nkwachi Nwamaghinna's photo

What is the Maximum Pairwise Product? It means that we have to find the maximum product of two distinct numbers in a given array of non-negative numbers.

Problem Statement

Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence.

Input format:

The first line of the input contains an integer n. The next line contains n non-negative integers a0,…,an−1 (separated by spaces).

Constraints:

2≤n≤2⋅105; 0≤a0,…,an−1≤105.

Output format:

Output a single number — the maximum pairwise product.

One approach is finding the two largest numbers in the array and storing their value in two variables and then multiplying both numbers but this approach makes you run into a problem when you have an array where the largest number is repeated e.g [2,5,9,9]. When finding the second largest number you compare against the largest number to ensure they aren't the same and you'll end up with 9 and 5 giving a maximum pairwise product of 45 instead of 81.

A better approach is to store the indices of the largest number and the second-largest number, this approach eliminates the error stated above.

My solution

Here is my solution implemented in Kotlin.

First of I created two variables to store the indices of the largest number and second-largest number. The next step was to find the largest number which was quite straightforward. When finding the second largest number I had to check if the index of the largest number is 0 and initialize the index of the second largest number to 1 instead or else I get 0 as the index of the second-largest number which is wrong.

Conclusion:

My solution has a complexity of O(n) but it can be better as I go through the array twice and it's possible to go through the array once while keeping track of the largest number and the second-largest number simultaneously. I intend to solve the algorithm using that approach so look out for part 2 on "Solving the Maximum Pairwise Product Algorithm".

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Pairwise Max Product

This python program takes user input of the number of elements in a list in the variable b and then takes user input of the list elements in list a . It then finds out the maximum product of a pair of the list elements.

For example, if the list elements are 5,4 and 6, then the maximum product is 30.

Can we simplify it in a way such that it takes less time than this?

The error I am getting is:

Failed case #4/17: time limit exceeded (Time used: 9.99/5.00, memory used: 22740992/2147483648.)
  • time-limit-exceeded

Sᴀᴍ Onᴇᴌᴀ's user avatar

Making it faster

The maximum product of two numbers in the input will be either:

  • the product of the two highest numbers
  • note that this is possible when the lowest numbers are negative

So you can find the two highest and two lowest values, and decide which product is higher and return it.

This can be done in \$O(n)\$ time, which will be much faster than the current \$O(n^2)\$ solution for large inputs.

Beware of corner cases

If there are less than two numbers, the program outputs 0. For a list with a single element, say [3] , printing that the maximum product of two pairs of numbers is 0 would seem strange.

Use descriptive variable names

It's hard to remember what is what, when variables don't have descriptive names, such as a and b . nums and nums_count would help a lot.

Use functions

The code reads input from stdin , computes something, then prints to stdout . The computation part can be turned into a function that takes a list of numbers and returns the maximum product. It will have a single responsibility, to compute the maximum product, and a reader can focus on making it fulfill that one responsibility:

Note that nums_count = len(nums) .

Follow the style guide

Python has an official style guide PEP-8 , it's good to follow it. For example, it's recommended to put spaces around operators, for example instead of range(i+1,b) , write range(i + 1, b) .

janos's user avatar

  • \$\begingroup\$ Thanks a lot! Turning down the complexity that way was helpful and also didn't think about the corner case! Thanks once again! \$\endgroup\$ –  Pratik Roy Commented Sep 23, 2022 at 21:45

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged python time-limit-exceeded or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • We spent a sprint addressing your requests — here’s how it went

Hot Network Questions

  • If Biden steps back or is replaced, until when must he do it?
  • Why does King Aegon speak to his dragon in the Common Tongue (English)?
  • How to reference a picture with two images?
  • Can I prettify a XML string using Apex?
  • How can I break an alignedat/gathered environment between pages?
  • Submitting 2 manuscripts explaining the same scientific fact but by two different methods
  • Citation hunting: Floer on spectral sequences
  • Can trills have 3 notes instead of two?
  • Time integration of first-order ODE with higher-order information
  • Is infinity a number?
  • Equivalence of first/second choice with naive probability - I don't buy it
  • Largest possible relative error
  • Using "Delight" Without a Preposition
  • Is a "single" cpu safer than multiple cores?
  • Why there is two different answers for the volume of a frustum?
  • Is this a Hadamard matrix?
  • Is "sinnate" a word? What does it mean?
  • Can I reuse a large part of my own previously published paper in a new paper?
  • Submission of a manuscript to two special issue of a journal
  • Why do jet aircraft need chocks when they have parking brakes?
  • Mathematical Induction over two numbers
  • Should I apologise to a professor after a gift authorship attempt, which they refused?
  • Why does IPC 2221 require so much more spacing at elevation?
  • 8x8 grid with no unmarked L-pentomino

assignment 1 maximum pairwise product

Search This Blog

Makingcodesimple.

Simple solutions with explanation for the problems on competitive sites like hackerearth and many many more things like how to make your code faster, shorter and simple only at makingcodesimple.blogspot.com

Coursera's Algorithmic toolbox assignment solutions( Sum of Two Digits, Maximum Pairwise Product ) :

Problem 1: sum of two digits, solution: (in c++), ( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder).

This code is simple. There's no need for any explanation.  

Problem 2: Maximum Pairwise Product

Guys , if you have any queries related to a question or need more explanation, comment down below!  

Post a Comment

Popular posts from this blog, hackerearth's basic programming solutions( seating arrangement, zoos, anagrams ) :, hackerearth's basic programming solutions( minimize cost, magical word, best index ) :.

assignment 1 maximum pairwise product

Coursera — Algorithmic Toolbox

Sharon Woo

Things I learnt from assignment 1 — max pairwise product problem:

  • The dreaded O(N)
  • Copying a list in Python is as simple as list.copy()
  • What a “naive solution” means

Sharon Woo

Written by Sharon Woo

Nerd runner

Text to speech

How to find Maximum Pairwise Product in Java using Naive approach

assignment 1 maximum pairwise product

In this Java tutorial, we will learn how to find the maximum pairwise product using Java. Maximum Pairwise Product in easy words you can say that it is the product of those two numbers present in an array from which we get the highest value possible.

What is the meaning of Maximum Pairwise Product?

It means that we have to find the maximum product of two distinct numbers in a given array of non-negative numbers.

Input : A sequence of non-negative numbers.

Output : The maximum value that can be obtained by multiplying two different numbers from the input sequence.

=>, For example, I’m giving you a sequence of non-negative numbers: a1 . . . . an

Input format:  The first line contains a single number whose value is equal to n. The next line contains n non-negative numbers a1 . . . . an.

Output format:  The maximum pairwise product.

Naive Method :

A naive approach is to solve the Maximum Pairwise Product Question is to find all the possible pairs from the sequence which is inputted by the user. A[1 . . . . n] =[a1 . . . . an] and then we have to find the largest product value.

First, we have to find the two largest values from the inputted sequence. Because we know that the product of the largest value is the maximum product we can get.

Note: All inputted numbers in the sequence is must be non-negative numbers.

Find Maximum Pairwise Product in Java using Native Approach

We have used StringTokenizer class here.

You can also read,

  • Frequency of Repeated words in a string in Java
  • Working with HashMap (Insertion, Deletion, Iteration) in Java

One response to “How to find Maximum Pairwise Product in Java using Naive approach”

After compiling it is showing illegal start of type ,I can’t solve this problem ….please help

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Please enable JavaScript to submit this form.

Related Posts

  • How to sort array elements alphabetically in Java?
  • Searching in a sorted and rotated array using Java
  • Create LinkedList from an array in Java

Bennett University

Algorithmic Toolbox

This course is part of Data Structures and Algorithms Specialization

Taught in English

Some content may not be translated

Neil Rhodes

Instructors: Neil Rhodes +5 more

Instructors

Instructor ratings

We asked all learners to give feedback on our instructors based on the quality of their teaching style.

Michael Levin

Sponsored by Bennett University

523,122 already enrolled

(12,395 reviews)

What you'll learn

Essential algorithmic techniques

Design efficient algorithms

Practice solving algorithmic interview problems

Implement efficient and reliable solutions

Details to know

assignment 1 maximum pairwise product

Add to your LinkedIn profile

See how employees at top companies are mastering in-demand skills

Placeholder

Build your subject-matter expertise

  • Learn new concepts from industry experts
  • Gain a foundational understanding of a subject or tool
  • Develop job-relevant skills with hands-on projects
  • Earn a shareable career certificate

Placeholder

Earn a career certificate

Add this credential to your LinkedIn profile, resume, or CV

Share it on social media and in your performance review

Placeholder

There are 6 modules in this course

This online course covers basic algorithmic techniques and ideas for computational problems arising frequently in practical applications: sorting and searching, divide and conquer, greedy algorithms, dynamic programming. We will learn a lot of theory: how to sort data and how it helps for searching; how to break a large problem into pieces and solve them recursively; when it makes sense to proceed greedily; how dynamic programming is used in genomic studies. You will practice solving computational problems, designing new algorithms, and implementing solutions efficiently (so that they run in less than a second).

Programming Challenges

Welcome to the first module of Data Structures and Algorithms! Here we will provide an overview of where algorithms and data structures are used (hint: everywhere) and walk you through a few sample programming challenges. The programming challenges represent an important (and often the most difficult!) part of this specialization because the only way to fully understand an algorithm is to implement it. Writing correct and efficient programs is hard; please don’t be surprised if they don’t work as you planned—our first programs did not work either! We will help you on your journey through the specialization by showing how to implement your first programming challenges. We will also introduce testing techniques that will help increase your chances of passing assignments on your first attempt. In case your program does not work as intended, we will show how to fix it, even if you don’t yet know which test your implementation is failing on.

What's included

6 videos 8 readings 1 quiz 2 programming assignments

6 videos • Total 48 minutes

  • Welcome! • 3 minutes • Preview module
  • Solving the Sum of Two Digits Programming Challenge (screencast) • 6 minutes
  • Solving the Maximum Pairwise Product Programming Challenge: Improving the Naive Solution, Testing, Debugging • 13 minutes
  • Stress Test - Implementation • 8 minutes
  • Stress Test - Find the Test and Debug • 7 minutes
  • Stress Test - More Testing, Submit and Pass! • 8 minutes

8 readings • Total 63 minutes

  • Ace Your Next Coding Interview • 10 minutes
  • What background knowledge is necessary? • 10 minutes
  • Social Networks and Microlearning • 1 minute
  • Optional Videos and Screencasts • 10 minutes
  • Alternative testing guide in Python • 10 minutes
  • Maximum Pairwise Product Programming Challenge • 10 minutes
  • Using PyCharm to solve programming challenges • 10 minutes
  • Acknowledgements • 2 minutes

1 quiz • Total 20 minutes

  • Solving Programming Challenges • 20 minutes

2 programming assignments • Total 180 minutes

  • Programming Assignment 1: Sum of Two Digits • 60 minutes
  • Programming Assignment 1: Maximum Pairwise Product • 120 minutes

Algorithmic Warm-up

In this module you will learn that programs based on efficient algorithms can solve the same problem billions of times faster than programs based on naïve algorithms. You will learn how to estimate the running time and memory of an algorithm without even implementing it. Armed with this knowledge, you will be able to compare various algorithms, select the most efficient ones, and finally implement them as our programming challenges!

12 videos 4 readings 3 quizzes 1 programming assignment 1 ungraded lab

12 videos • Total 77 minutes

  • Why Study Algorithms? • 7 minutes • Preview module
  • Coming Up • 3 minutes
  • Problem Overview • 3 minutes
  • Naive Algorithm • 5 minutes
  • Efficient Algorithm • 3 minutes
  • Problem Overview and Naive Algorithm • 4 minutes
  • Efficient Algorithm • 5 minutes
  • Computing Runtimes • 10 minutes
  • Asymptotic Notation • 6 minutes
  • Big-O Notation • 6 minutes
  • Using Big-O • 10 minutes
  • Course Overview • 10 minutes

4 readings • Total 16 minutes

  • Resources • 2 minutes
  • Interview Questions • 10 minutes

3 quizzes • Total 30 minutes

  • Logarithms • 10 minutes
  • Big-O • 10 minutes
  • Growth rate • 10 minutes

1 programming assignment • Total 150 minutes

  • Programming Assignment 2: Algorithmic Warm-up • 150 minutes

1 ungraded lab • Total 60 minutes

  • Big-O Notation: Plots • 60 minutes

Greedy Algorithms

In this module you will learn about seemingly naïve yet powerful class of algorithms called greedy algorithms. After you will learn the key idea behind the greedy algorithms, you may feel that they represent the algorithmic Swiss army knife that can be applied to solve nearly all programming challenges in this course. But be warned: with a few exceptions that we will cover, this intuitive idea rarely works in practice! For this reason, it is important to prove that a greedy algorithm always produces an optimal solution before using this algorithm. In the end of this module, we will test your intuition and taste for greedy algorithms by offering several programming challenges.

10 videos 9 readings 5 quizzes 1 programming assignment

10 videos • Total 63 minutes

  • Largest Number • 3 minutes • Preview module
  • Queue of Patients • 11 minutes
  • Implementation and Analysis • 7 minutes
  • Main Ingredients of Greedy Algorithms • 1 minute
  • Celebration Party Problem • 3 minutes
  • Greedy Algorithm • 5 minutes
  • Implementation and Analysis • 5 minutes
  • Maximizing Loot • 8 minutes
  • Implementation and Analysis • 10 minutes
  • Review • 4 minutes

9 readings • Total 90 minutes

  • Examples • 10 minutes
  • Local vs Global Optimum • 10 minutes
  • Proving Correctness of Greedy Algorithms • 10 minutes
  • Implementation • 10 minutes
  • Money Change • 10 minutes
  • Solution: Use the Largest Denomination First • 10 minutes
  • Proving Correctness • 10 minutes
  • Maximizing the Value of the Loot Problem • 10 minutes
  • Solution: Take as Much of the Most Expensive Compound as You Can • 10 minutes

5 quizzes • Total 150 minutes

  • Largest Concatenate • 30 minutes
  • Money Change • 30 minutes
  • Puzzle: Balls in boxes • 30 minutes
  • Puzzle: Activity Selection • 30 minutes
  • Puzzle: Touch All Segments • 30 minutes

1 programming assignment • Total 180 minutes

  • Programming Assignment 3: Greedy Algorithms • 180 minutes

Divide-and-Conquer

In this module you will learn about a powerful algorithmic technique called Divide and Conquer. Based on this technique, you will see how to search huge databases millions of times faster than using naïve linear search. You will even learn that the standard way to multiply numbers (that you learned in the grade school) is far from the being the fastest! We will then apply the divide-and-conquer technique to design two efficient algorithms (merge sort and quick sort) for sorting huge lists, a problem that finds many applications in practice. Finally, we will show that these two algorithms are optimal, that is, no algorithm can sort faster!

20 videos 5 readings 8 quizzes 1 programming assignment

20 videos • Total 157 minutes

  • Intro • 3 minutes • Preview module
  • Linear Search • 7 minutes
  • Binary Search • 7 minutes
  • Binary Search Runtime • 8 minutes
  • Problem Overview and Naïve Solution • 6 minutes
  • Naïve Divide and Conquer Algorithm • 7 minutes
  • Faster Divide and Conquer Algorithm • 6 minutes
  • What is the Master Theorem? • 4 minutes
  • Proof of the Master Theorem • 9 minutes
  • Problem Overview • 2 minutes
  • Selection Sort • 8 minutes
  • Merge Sort • 10 minutes
  • Lower Bound for Comparison Based Sorting • 12 minutes
  • Non-Comparison Based Sorting Algorithms • 7 minutes
  • Overview • 2 minutes
  • Algorithm • 9 minutes
  • Random Pivot • 13 minutes
  • Running Time Analysis (optional) • 15 minutes
  • Equal Elements • 6 minutes
  • Final Remarks • 8 minutes

5 readings • Total 40 minutes

  • Resources • 10 minutes
  • Resources • 5 minutes

8 quizzes • Total 155 minutes

  • Linear Search and Binary Search • 10 minutes
  • Puzzle: 21 questions game • 30 minutes
  • Puzzle: Two Adjacent Cells of Opposite Colors • 30 minutes
  • Polynomial Multiplication • 15 minutes
  • Master Theorem • 10 minutes
  • Sorting • 15 minutes
  • Quick Sort • 15 minutes
  • Puzzle: Local Maximum • 30 minutes
  • Programming Assignment 4: Divide and Conquer • 180 minutes

Dynamic Programming 1

In this final module of the course you will learn about the powerful algorithmic technique for solving many optimization problems called Dynamic Programming. It turned out that dynamic programming can solve many problems that evade all attempts to solve them using greedy or divide-and-conquer strategy. There are countless applications of dynamic programming in practice: from maximizing the advertisement revenue of a TV station, to search for similar Internet pages, to gene finding (the problem where biologists need to find the minimum number of mutations to transform one gene into another). You will learn how the same idea helps to automatically make spelling corrections and to show the differences between two versions of the same text.

4 videos 2 readings 6 quizzes 1 programming assignment

4 videos • Total 30 minutes

  • Change Problem • 10 minutes • Preview module
  • The Alignment Game • 8 minutes
  • Computing Edit Distance • 6 minutes
  • Reconstructing an Optimal Alignment • 4 minutes

2 readings • Total 10 minutes

6 quizzes • total 180 minutes.

  • Change Money • 30 minutes
  • Puzzle: Number of Paths • 30 minutes
  • Puzzle: Two Rocks Game • 30 minutes
  • Puzzle: Three Rocks Game • 30 minutes
  • Edit Distance • 30 minutes
  • Puzzle: Primitive Calculator • 30 minutes

1 programming assignment • Total 240 minutes

  • Programming Assignment 5: Dynamic Programming 1 • 240 minutes

Dynamic Programming 2

In this module, we continue practicing implementing dynamic programming solutions.

8 videos 2 readings 2 quizzes 1 programming assignment

8 videos • Total 77 minutes

  • Problem Overview • 5 minutes • Preview module
  • Knapsack with Repetitions • 10 minutes
  • Knapsack without Repetitions • 18 minutes
  • Final Remarks • 7 minutes
  • Problem Overview • 7 minutes
  • Subproblems • 6 minutes
  • Algorithm • 12 minutes
  • Reconstructing a Solution • 8 minutes

2 readings • Total 5 minutes

  • Polynomial vs Pseudopolynomial • 0 minutes

2 quizzes • Total 20 minutes

  • Knapsack • 10 minutes
  • Maximum Value of an Arithmetic Expression • 10 minutes
  • Programming Assignment 6: Dynamic Programming 2 • 180 minutes

assignment 1 maximum pairwise product

UC San Diego is an academic powerhouse and economic engine, recognized as one of the top 10 public universities by U.S. News and World Report. Innovation is central to who we are and what we do. Here, students learn that knowledge isn't just acquired in the classroom—life is their laboratory.

Why people choose Coursera for their career

assignment 1 maximum pairwise product

Learner reviews

Showing 3 of 12395

12,395 reviews

Reviewed on Mar 6, 2017

This is a very useful very rich algorithms course, it is one of the best i have ever attended online, i would really recommend this course to any one who wants a challenging algorithms program.

Reviewed on Jul 6, 2020

Pretty good course on algos . I have already done algorithms in college and know in depth about it and is doing it to get a certificate just for a job .

I am impressed by the way of teaching .

Reviewed on Aug 15, 2020

Great Course. This series is great but sometimes you will get frustrated because of the questions as it is not easy, make sure to give those a time. Great satisfaction after solving them though

Recommended if you're interested in Computer Science

assignment 1 maximum pairwise product

Writing Java Application Code

assignment 1 maximum pairwise product

The Java Language

assignment 1 maximum pairwise product

Introduction to Java as a Second Language

assignment 1 maximum pairwise product

Mobile Development and JavaScript

Placeholder

Open new doors with Coursera Plus

Unlimited access to 7,000+ world-class courses, hands-on projects, and job-ready certificate programs - all included in your subscription

Advance your career with an online degree

Earn a degree from world-class universities - 100% online

Join over 3,400 global companies that choose Coursera for Business

Upskill your employees to excel in the digital economy

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

max_pairwise_product.cpp

Latest commit, file metadata and controls.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

problem calculating the Maximum Pairwise Product C++

This is my code for the maximum pairwise product. It takes an array of numbers, sorts them to find the first and second maximum numbers, then return the product of them. The code works for small arrays and small values. But it fails with some numbers, and also it epically fails with large numbers such as 10000 and so.

i thought it was a problem with the data type i used, so i defined the data type to be int_64t so it can handle large numbers, but still i get the same wrong results! Can anyone help me with that?

Fezofchekov's user avatar

  • 1 Can you clarify what you mean by "epically fails"? –  blackbrandt Commented Jun 23, 2019 at 23:11
  • For example when i give it an array of 5 numbers consisting of 10000, 10,1,2,3..it's supposed to return 100000, instead it gives me some random large number, something like 17346274 or something. –  Fezofchekov Commented Jun 23, 2019 at 23:20
  • 1 The error is here: for (int j=0; j<=n; j++) . Should be j < n . Same for another loop. –  user2956272 Commented Jun 23, 2019 at 23:22
  • UPDATE: Now the code works fine with large numbers like 10000 and so, but it fails with small numbers! I tried a set of 3 numbers consisting of 1 2 3, it gave me a result of 9! while it was supposed to give 2*3=6, any ideas? –  Fezofchekov Commented Jun 23, 2019 at 23:55
  • What is the meaning of this line: if(maxind1!=j && maxind2==-1 || numbers[j]>numbers[maxind2]) ? It could be a precedence problem. You may want to add parenthesis. –  user10957435 Commented Jun 24, 2019 at 0:14

2 Answers 2

(EDITED as per comments from others)

Besides what @dyukha noted - for (int j=0; j<=n; j++) - also: maxind2 could be negative in the code below, which is used to subscript the vector.

Solution is to change the precedence in logical expression inside if to:

v01d's user avatar

  • Actually the first if is fine, because C++ uses Short-circuit evaluation , which means that if maxind1==-1 is true, the part after || is not even evaluated. But it's true that the second if has a problem: if maxind1!=j is false, it will evaluate numbers[-1] . Solution: use parentheses to change the precedence, that is, if(maxind1!=j && (maxind2==-1 || numbers[j]>numbers[maxind2])) . Which is, by the way, what Chipster said in the comments. –  Fabio says Reinstate Monica Commented Jun 24, 2019 at 0:38
  • @FabioTurati yes I didn't pay attention on the first. Also, didn't know the (what i see as standard logical ops) are called short-circuit. –  v01d Commented Jun 24, 2019 at 0:45
  • In a logical OR, if the first is true, then you are sure the whole OR expression will be true, and this is due to the very nature of OR. It is like this in every language. What short-circuiting adds is that, in such cases, the second part is not even evaluated, as it would be a waste of time. This prevents some problems, as in this case. A typical example, when you have a pointer p , is: if (p && p->do_something()) . If p is null, evaluating the second part would lead to Undefined Behaviour (probably a segmentation fault), but short circuiting prevents it and makes this code safe to run. –  Fabio says Reinstate Monica Commented Jun 24, 2019 at 0:54
  • @FabioTurati understand that, but I never heard term "short-circuit" is what's this called, or that that's a feature. I thought that's standard logic –  v01d Commented Jun 24, 2019 at 0:55
  • 1 @Rania Please remember that if an answer solves your problem you should mark it as accepted, by clicking on the tick on its left. Thank you! –  Fabio says Reinstate Monica Commented Jun 24, 2019 at 8:59

SOLVED Thank you all for helping me out, it finally worked properly. The source of the problem was that i didn't use parenthesis in the second if conditions, and the condition of the for loop (use < instead of <=) Code after solving the errors:

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged c++ or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • How to view logs of deleted folders
  • Does the number of parameters in the model affect its intelligence?
  • What enforcement exists for medical informed consent?
  • Can I prettify a XML string using Apex?
  • Interesting structure: ".....ever go to do... ! --- "If you ever go to sell this place, let me know."
  • Understanding top memory bar
  • Integrated Portal to seek public transport connections in the UK, preferably with prices
  • Why does IPC 2221 require so much more spacing at elevation?
  • Error concerning projectile motion in respected textbook?
  • Sci fi book that has a tunnel. Depending on where you go through wall, go to different planet
  • The rear wheel from my new Road Bike vibrates strongly
  • Why does black have a higher win rate in Exchange French?
  • Is it possible to have multiple versions of MacOS on the same laptop at the same time?
  • Submitting 2 manuscripts explaining the same scientific fact but by two different methods
  • Is it possible with modern-day technology to expand an already built bunker further below without the risk of collapsing the entire bunker?
  • Can Black Lotus alone enable the Turn 1 Channel-Fireball combo?
  • Does the damage from Thunderwave occur before or after the target is moved
  • Did Joe Biden refer to himself as a black woman?
  • 8x8 grid with no unmarked L-pentomino
  • When, if ever, is bribery legal?
  • Real-life problems involving solving triangles
  • How should I deal with curves in new deck boards during installation?
  • DHCP assigned addresses following devices/users and routing
  • Why does King Aegon speak to his dragon in the Common Tongue (English)?

assignment 1 maximum pairwise product

Algorithmic Toolbox | Week 1

Course Name: Algorithmic Toolbox

Course Link: Algorithmic Toolbox

These are Algorithmic Toolbox Week 1 Programming Assignment Coursera Answers

Programming Assignment: Programming Assignment 1: Sum of Two Digits

1-1: Sum of Two Digits

Answer: Please login to see answer .

Programming Assignment: Programming Assignment 1: Maximum Pairwise Product

1-2: Maximum Pairwise Product

More Weeks of the course: Click Here

More Coursera courses: https://progiez.com/coursera

Algorithmic Toolbox Week 1 Programming Assignment

The content uploaded on this website is for reference purposes only. Please do it yourself first.

IMAGES

  1. Maximum Pairwise Product

    assignment 1 maximum pairwise product

  2. Maximum Pairwise Product Algorithm

    assignment 1 maximum pairwise product

  3. Maximum Pairwise Product Algorithm

    assignment 1 maximum pairwise product

  4. Solved Problem 1 [2pts] Find the pairwise dot products of

    assignment 1 maximum pairwise product

  5. Testing for Maximum Pairwise Product: Positive and Negative

    assignment 1 maximum pairwise product

  6. The maximum pairwise product · For loop and ranges · Hyperskill

    assignment 1 maximum pairwise product

VIDEO

  1. How to Fit Multivariate Multiple Linear Regression in SPSS

  2. MAX & MIN Problem

  3. Factorial ANOVA in R is Quite Easy

  4. Let P(x) be polynomial of degree atmost 5 which leaves remainders -1 and 1 upon division by (x-1)

  5. Max Dot Product Of Two Subsequences

  6. 🎄 Advent of code 2023 in F#

COMMENTS

  1. 1.2 max pairwise product.py

    This repository contains all the solutions for the assignments of the course - Algorithmic Toolbox offered on Coursera. - anoubhav/Coursera-Algorithmic-Toolbox

  2. Abd-ELrahmanHamza/Algorithmic-Toolbox

    Programming Assignment 1: Programming Challenges (OPTIONAL) Solving The Maximum Pairwise Product Programming Challenge in C++; Maximum Pairwise Product Programming Challenge; Using PyCharm to solve programming challenges (optional experimental feature) Acknowledgements (Optional)

  3. python

    Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, max0≤i≠j≤n−1aiaj). Different elements here mean ai and aj with i≠j (it can be the case that ai=aj). Input format.

  4. anoubhav/Coursera-Algorithmic-Toolbox

    The assignment solutions are in Python3. Disclaimer: ... Week 1- Programming Challenges . Sum of Two Digits; Maximum Pairwise Product; Week 2- Algorithmic Warm-up . Fibonacci Number; Last Digit of a Large Fibonacci Number; Greatest Common Divisor; ... (Maximum Dot Product) Collecting Signatures (Covering Segments by Points) Maximum Number of ...

  5. assignment solutions/1.2 max pairwise product.py · master · rithik

    assignment solutions; 1.2 max pairwise product.py; Find file Blame History Permalink added folder assignment solutions. Moved all files to that folder · 1f7cd5cb Anoubhav Agarwaal authored Sep 12, 2018.

  6. Maximum Pairwise Product

    Output: The maximum value that can be obtained by multiplying two different elements from the sequence. Given a sequence of non-negative numbers a 1, …, a n, compute. max 1 ≤ i ≠ j ≤ na ia j. i and j should be different, although a i and a j might be equal. the maximum pairwise product from the input.

  7. Maximum pairwise product

    For example, if we have the list [1; 3; 5; -2] the maximum pairwise product is 15, which is the product of 3 and 5. The straigt-forward approach is to compute all possible pairwise products and identify the maximum among the intermediate results: long long MaxPairwiseProduct(const vector<int>& numbers) { long long result = 0; // result to hold ...

  8. Solving the Maximum Pairwise Product Algorithm

    It means that we have to find the maximum product of two distinct numbers in a given array of non-negative numbers. Problem Statement. Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence. Input format:

  9. python

    So you can find the two highest and two lowest values, and decide which product is higher and return it. This can be done in O(n) O n time, which will be much faster than the current O(n2) O n 2 solution for large inputs. def pairwise_max_product(nums): """. >>> pairwise_max_product([3, 2])

  10. mablatnik/Algorithmic-Toolbox

    This repository will contain my work from the Master Algorithmic Programming Techniques Specialization that was created by UC San Diego and delivered through Coursera. - mablatnik/Algorithmic-Toolbox

  11. Coursera's Algorithmic toolbox assignment solutions( Sum of ...

    Simple solutions for coursera's Algorithmic toolbox assignment questions: Sum of Two Digits, Maximum Pairwise Product by Making code simple! ... Problem 2: Maximum Pairwise Product Solution: (in c++) ( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder) ...

  12. Coursera

    Things I learnt from assignment 1 — max pairwise product problem: The dreaded O(N) Copying a list in Python is as simple as list.copy() What a "naive solution" means;

  13. Algorithmic Toolbox

    Solving the Maximum Pairwise Product Programming Challenge: Improving the Naive Solution, Testing, ... Programming Assignment 1: Maximum Pairwise Product ...

  14. Python Maximum Pairwise Fast Solution [dup]

    Show activity on this post. When max number is on position 0, you will get both max_index1 and max_index2 as 0. That's why you are getting like this . Add the following lines before #find the second highest number in pairwise1 function . if max_index1==0: max_index2=1. else: max_index2=0.

  15. Coursera-Algorithmic-Toolbox-1/assignment solutions/1.2 max pairwise

    This repository contains all the solutions for the assignments of the course - Algorithmic Toolbox offered on Coursera. - tjanhvi/Coursera-Algorithmic-Toolbox-1

  16. Find Maximum Pairwise Product in Java

    Output format: The maximum pairwise product. Sample 1. Input: 3 1 2 3. Output: 6. Sample 2. Input: 10 7 5 14 2 8 8 10 1 2 3. Output: 140. Naive Method : A naive approach is to solve the Maximum Pairwise Product Question is to find all the possible pairs from the sequence which is inputted by the user. A[1 . . . . n] =[a1 . . . . an] and then we ...

  17. Maximum Pairwise Product.png

    View Maximum Pairwise Product.png from ENG 04 at Mapúa Institute of Technology. C Programming Assignment 1: Max

  18. Algorithmic Toolbox

    Solving the Maximum Pairwise Product Programming Challenge: Improving the Naive Solution, Testing, ... Programming Assignment 1: Maximum Pairwise Product ...

  19. Algorithmic-Toolbox/algorithmic_toolbox/week_1/maximum_pairwise_product

    This repository will contain my work from the Master Algorithmic Programming Techniques Specialization that was created by UC San Diego and delivered through Coursera. - mablatnik/Algorithmic-Toolbox

  20. problem calculating the Maximum Pairwise Product C++

    0. This is my code for the maximum pairwise product. It takes an array of numbers, sorts them to find the first and second maximum numbers, then return the product of them. The code works for small arrays and small values. But it fails with some numbers, and also it epically fails with large numbers such as 10000 and so.

  21. Algorithmic Toolbox Week 1 Programming Assignment Coursera

    Programming Assignment: Programming Assignment 1: Maximum Pairwise Product. 1-2: Maximum Pairwise Product. Answer: Please login to see answer. These are Algorithmic Toolbox Week 1 Programming Assignment Coursera Answers. More Weeks of the course: Click Here.