DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #306 - Largest Possible Product

Given an array of integers, find the largest possible product obtained by multiplying two adjacent numbers in an array.

Examples

adjacentProduct([1, 2, 3]) ==> returns 6
adjacentProduct([3, 4, 5]) ==> returns 20

Tests

adjacentProduct([3, 7, 9])
adjacentProduct([-3, -4, 15])
adjacentProduct([-4, -1, -10])

Good luck!


This challenge comes from MrZizoScream on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (12)

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Rust

#![feature(array_windows)]
pub fn adjacent_product1(nums: &[usize]) -> Option<usize> {
    nums.array_windows().map(|[a, b]| a * b).max()
}
Enter fullscreen mode Exit fullscreen mode

on stable you have the options of instead doing:

pub fn adjacent_product(nums: &[usize]) -> Option<usize> {
    nums.windows(2)
        .filter_map(|slice| match slice {
            [a, b] => Some(a * b),
            _ => None,
        })
        .max()
}
Enter fullscreen mode Exit fullscreen mode

or

pub fn adjacent_product(nums: &[usize]) -> Option<usize> {
    nums.windows(2)
        .map(|slice| match slice {
            [a, b] => a * b,
            _ => unreachable!(), // this could panic at runtime if it could actually be reached
        })
        .max()
}
Enter fullscreen mode Exit fullscreen mode

which produce identical assembly to each other in release mode (meaning the compiler proves different sized slices unreachable without your help)

Generic:

#![feature(array_windows)]
use std::{cmp::Ord, ops::Mul};
pub fn adjacent_product<'a, T: 'a, R>(nums: &'a [T]) -> Option<R>
where
    R: Ord,
    &'a T: Mul<Output = R>,
{
    nums.array_windows().map(|[a, b]| a * b).max()
}
Enter fullscreen mode Exit fullscreen mode

Haha square meters go brr

#[derive(Debug)]
struct M(u8);
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct M2(u16);
impl Mul<Self> for &M {
    type Output = M2;
    fn mul(self, rhs: Self) -> M2 {
        M2((self.0 as u16) * (rhs.0 as u16))
    }
}
fn main() {
    let pogs = [4, 1, 3, 3, 2].map(M);
    println!("{:?} {:?}", &pogs, adjacent_product(&pogs));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mrwebuzb profile image
Asliddinbek Azizovich

Golang solution

func adjacentProduct(nums []int) int {
    curr, max := nums[0], 0
    for i := 1; i < len(nums); i++ {
        curr = curr * nums[i]
        if max < curr {
            max = curr
        }
        curr = nums[i]
    }
    return max
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
agtoever profile image
agtoever • Edited

Python 3 oneliner with testcases and TIO link:

adjacentProduct = lambda arr: max(arr[i] * arr[i+1] for i in range(len(arr) - 1))

cases = [
    ([1, 2, 3], 6),
    ([3, 4, 5], 20),
    ([3, 7, 9], None),
    ([-3, -4, 15], None),
    ([-4, -1, -10], None),
]

for arg, ans in cases:
    print(f"adjacentProduct({arg}) = {adjacentProduct(arg)}{f'; answer should be: {ans}' if ans else ''}.")

if all(adjacentProduct(arg) == ans for arg, ans in cases if ans):
    print('All test cases are correct')
else:
    print('NOT all test cases are correct')
Enter fullscreen mode Exit fullscreen mode

Try it online!

Collapse
 
gugod profile image
Kang-min Liu

Perl

sub adjacentProduct {
    my @nums = @{ $_[0] };
    my $max = 0;
    for my $i (0..@nums-2) {
        my $p = $nums[$i] * $nums[$i+1];
        $max = $p if $max < $p;
    }
    return $max;
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
aminnairi profile image
Amin

C

int adjacentProduct(int numbers[], unsigned int length) {
    int maximum = 0;

    for (unsigned int index = 0; index < length; index++) {
        int indexNext = index + 1;

        if (indexNext == length) {
            break;
        }

        int current = numbers[index];
        int next = numbers[indexNext];
        int product = current * next;

        if (product > maximum) {
            maximum = product;
        }
    }

    return maximum;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grglldz profile image
Guiorgui • Edited
function adjacentProduct(a) {
    const result = [];
    for(let i = 0, len = a.length - 1; i < len; i++) {
        result.push(a[i] * a[i+1]);
    }
    return Math.max(...result);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
_bkeren profile image
''

JS

const adjacentProduct = arr => arr
  .slice(0, -1)
  .reduce(
    (max, n, i) => Math.max(max, n * arr[i + 1]), -Infinity
  )


Enter fullscreen mode Exit fullscreen mode
Collapse
 
peter279k profile image
peter279k

Here is the simple solution in PHP:

function adjacentElementsProduct($array) {
  $max = [];
  foreach ($array as $number) {
    $next = next($array);
    if ($next === false) {
      break;
    }
    $max[] = $number * $next;
  }

  return max($max);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
willsmart profile image
willsmart • Edited

A KISS version in typescript...

function greatestProductOfAdjacentPair(arr: number[]): number | undefined {
  let max: number | undefined;
  for (let i = arr.length - 2; i >= 0; i--) {
    max = Math.max(max ?? -Infinity, arr[i] * arr[i + 1]);
  }
  return max;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
baenencalin profile image
Calin Baenen

What counts as adjacent? Neighboring?
Like the tests, I'm gonna assume that this only takes 3 inputs.
But, Java:

class Utils {
    public static Number adjacent_product(float x, float y, float z) {
        return y*Math.max(x, z);
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

JS

const adjacentProduct=a=>Math.max(...a.map((m,i)=>m*(a.slice(1)[i]>>0)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jehielmartinez profile image
Jehiel Martinez

JS

largestProduct = (arr) => {
  const results = []
  for (i=0; i<arr.length-1; i++){
    results.push(arr[i] * arr[i+1])
  }
  return Math.max(...results)
}
Enter fullscreen mode Exit fullscreen mode