$cache[$key] = empty($arr) ? NULL : $arr; return $cache[$key]; } // 门户 获取需要在频道显示的栏目主题数据 function portal_channel_thread($fid) { global $forumlist; if (empty($fid)) return NULL; $orderby = array('tid' => 1); $page = 1; // 遍历所有在频道显示内容的栏目 $category_forumlist = channel_category($fid); $arrlist = array(); $forum_tids = array(); $tidlist = array(); if ($category_forumlist) { foreach ($category_forumlist as &$_forum) { // 频道显示数据 $arrlist['list'][$_forum['fid']] = array( 'fid' => $_forum['fid'], 'name' => $_forum['name'], 'rank' => $_forum['rank'], 'type' => $_forum['type'], 'url' => $_forum['url'], 'channel_new' => $_forum['channel_new'], ); $forum_thread = thread_tid__find(array('fid' => $_forum['fid']), $orderby, $page, $_forum['channel_new'], 'tid', array('tid')); // 最新信息按栏目分组 foreach ($forum_thread as $key => $_thread) { $forum_tids[$key] = $_thread; } unset($forum_thread); } $tidlist += $forum_tids; } unset($category_forumlist); // 获取属性对应的tid集合 list($flaglist, $flagtids) = flag_thread_by_fid($fid); empty($flagtids) || $tidlist += $flagtids; unset($flagtids); // 频道置顶 $stickylist = sticky_list_thread($fid); empty($stickylist) || $tidlist += $stickylist; // 在这之前合并所有二维数组 tid值为键/array('tid值' => tid值) $tidarr = arrlist_values($tidlist, 'tid'); // 在这之前使用$tidarr = array_merge($tidarr, $arr)前合并所有一维数组 tid/array(1,2,3) if (empty($tidarr)) { $arrlist['list'] = isset($arrlist['list']) ? array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid') : array(); return $arrlist; } $tidarr = array_unique($tidarr); $pagesize = count($tidarr); // 遍历获取的所有tid主题 $threadlist = well_thread_find_asc($tidarr, $pagesize); // 遍历时为升序,翻转为降序 $threadlist = array_reverse($threadlist); foreach ($threadlist as &$_thread) { // 各栏目最新内容 isset($forum_tids[$_thread['tid']]) AND $arrlist['list'][$_thread['fid']]['news'][$_thread['tid']] = $_thread; // 全站置顶内容 isset($stickylist[$_thread['tid']]) AND $arrlist['sticky'][$_thread['tid']] = $_thread; // 首页属性主题 if (!empty($flaglist)) { foreach ($flaglist as $key => $val) { if (isset($val['tids']) && in_array($_thread['tid'], $val['tids'])) { $arrlist['flaglist'][$key][array_search($_thread['tid'], $val['tids'])] = $_thread; ksort($arrlist['flaglist'][$key]); $arrlist['flag'][$_thread['tid']] = $_thread; } } } } unset($threadlist); if (isset($arrlist['sticky'])) { $i = 0; foreach ($arrlist['sticky'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flag'])) { $i = 0; foreach ($arrlist['flag'] as &$val) { ++$i; $val['i'] = $i; } } if (isset($arrlist['flaglist'])) { foreach ($arrlist['flaglist'] as &$val) { $i = 0; foreach ($val as &$v) { ++$i; $v['i'] = $i; } } } isset($arrlist['list']) AND $arrlist['list'] = array_multisort_key($arrlist['list'], 'rank', FALSE, 'fid'); return $arrlist; } ?>arrays - Javascript: adjacent Elements Product algorithm - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript: adjacent Elements Product algorithm - Stack Overflow

programmeradmin0浏览0评论

I'm trying to solve a basic javascript algorithm and i'm kinda stuck, here is the question:

Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.

Example

For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.

7 and 3 produce the largest product.

Here is my code, i can't find the problem but in the tests it says that it returns null:

    function adjacentElementsProduct(inputArray) {
    var cb;
    for(var i=0;i<inputArray.length;i++){
      if(inputArray[i] !== inputArray[inputArray.length-1]){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
      }
    }
  return cb;
  }

What is my problem and what i need to change?

I'm trying to solve a basic javascript algorithm and i'm kinda stuck, here is the question:

Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.

Example

For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.

7 and 3 produce the largest product.

Here is my code, i can't find the problem but in the tests it says that it returns null:

    function adjacentElementsProduct(inputArray) {
    var cb;
    for(var i=0;i<inputArray.length;i++){
      if(inputArray[i] !== inputArray[inputArray.length-1]){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
      }
    }
  return cb;
  }

What is my problem and what i need to change?

Share Improve this question edited Oct 22, 2017 at 14:35 asked Oct 22, 2017 at 14:30 user8142459user8142459 7
  • 2 Either the array is empty or at least one of the two if conditions are always preventing the assignment. Did you try stepping through the code while it's running so as to examine the values? – llama Commented Oct 22, 2017 at 14:33
  • You update cb only when the first number is equal to the last number in the array. That condition is true for the last element, in which case you access inputArray[inputArray.length], which isn't a valid index. – M Oehm Commented Oct 22, 2017 at 14:33
  • @llama I changed it, thank you i didn't notice that, but the function still returns null. – user8142459 Commented Oct 22, 2017 at 14:35
  • What are you trying to achieve with if(inputArray[i] !== inputArray[inputArray.length-1])? – Sebastian Simon Commented Oct 22, 2017 at 14:35
  • @Xufox I tried to prevent the function from continuing to do things when the loop is at its last item, I don't really know what it would do if it would get to the last item but i did it just in case. – user8142459 Commented Oct 22, 2017 at 14:39
 |  Show 2 more comments

9 Answers 9

Reset to default 7

What you ultimately want to do is iterate through the array excluding the last member, and compare a product of each current item with its next adjacent member to that of the largest one found thus far.

You can use .slice() and .reduce() for this.

function adjacentElementsProduct(arr) {
  return arr.slice(0, -1)
            .reduce((max, n, i) => Math.max(max, n * arr[i + 1]), -Infinity)
}


console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));


An alternate solution would be to create an array of products using .map() after doing the same .slice(), and pass that array's members to Math.max.

function adjacentElementsProduct(arr) {
  return Math.max(...arr.slice(0, -1).map((n, i) => n * arr[i + 1]))
}


console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

The problem with your code is you never initialized cb. So the comparison with cb is always invalid. Here is the correct version of your code -

function adjacentElementsProduct(inputArray) {
    var cb = Number.NEGATIVE_INFINITY;
    for(var i=0;i<inputArray.length-1;i++){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
    }
  return cb;
}

console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 7]))

Since you need to use pairs of elements - you can just run through it and keep store maximum product value, something like this:

function adjacentElementsProduct(items) {
    var product = 0;
    for (var i = 0; i < items.length - 1; i++) {
        product = Math.max(product, items[i] * items[i + 1]);
    }
    return product;
}

console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

Using reduce we can simplify the amount of code.

var a = [3, 6, -2, -2, 7, 3].reduce(function(a, b, i, arr){
  if (b*arr[i-1] > a)
  {
      a = b*arr[i-1];
  }

  return a;
})

console.log(a)

First of all, you could iterate from index 1 to the end and use i - 1 and i for adjacent elements. Then you could check if you are in iteration one and take the value or if the multiplication is greater then the old value, then assing the greater product.

function adjacentElementsProduct(inputArray) {
    var cb, i;
    for (i = 1; i < inputArray.length; i++) {
        if (i === 1 || inputArray[i - 1] * inputArray[i] > cb) {
            cb = inputArray[i - 1] * inputArray[i];
        }
    }
    return cb;
}

console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

More generic solution: This will work for every array with negatives and non negatives numbers.

int adjacentElementsProduct(int[] inputArray) {

    int length = inputArray.Length;
    int max = Number.NEGATIVE_INFINITY;

    for (int i = 0; i < length - 1; i++ ) {
        max = Math.Max(max, inputArray[i] * inputArray[i+1]);
    }

    return max;
}
int adjacentElementsProduct(std::vector<int> inputArray) {
    int n=inputArray.size();
 int p=1;
 int maxp=inputArray[0]*inputArray[1];
    for(int i=0;i<n-1;i++){
       p=inputArray[i]*inputArray[i+1]; 
       if(p>maxp){
           maxp=p;
       }       
    }
    
    return maxp;
}

Here is how you will do that in Python:

 def adjacentElementsProduct(inputArray):
    max = inputArray[0]* inputArray[1]
    for i in range(0, len(inputArray)-1):
            if inputArray[i] * inputArray[i+1] > max :
                max = inputArray[i] * inputArray[i+1]
                i+1
            else:
                i+1
    return max  

Or you can do it in one line like:

def adjacentElementsProduct(inputArray):
    return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])

        
function largetProduct(inputArray) {
   let pairs=[];
     for(var i = 0;i<inputArray.length ;i+=2){
         pairs.push(inputArray.slice(i,i+2))
     }


    let products = pairs.map(v=> v[0]*v[1] || 1);
        return (Math.max.apply(0,products));
 }
发布评论

评论列表(0)

  1. 暂无评论