找出数组的最大差异

时间:2015-04-12 03:36:29

标签: javascript

我正在使用一种算法来返回任意一对数字的差异 ,以便该对中的较大整数出现在较高的索引处(在数组中)比较小的整数

示例......

数组:[2,3,10,2,4,8,1]

解决方案:10 - 2 = 8

输出:8


数组:[7,9,5,6,3,2]

解决方案:9 - 7 = 2

输出:2


这是我所拥有的,但它并不适用于所有测试...

var a = [22, 2, 4, 5, 6, 444, 1, 666];

// declare variables
var minNumber = a[0],                   // initilize to first element
    maxNumber = a[0],                   // --- ^
    minNumberIndex = 0,                 // min index
    maxNumberIndex = a.length - 1;      // max index

// loop through each element in array
for(i = 0; i < a.length; i++) {

    // find min
    if (a[i] < minNumber && i < maxNumberIndex) {
        minNumber = a[i];
        minNumberIndex = i;
    }

    // find max
    if (a[i] >= maxNumber && i > minNumberIndex) {
        maxNumber = a[i];
        maxNumberIndex = i;
    }
}

// return results
console.log("max: \t" + maxNumber);
console.log("min: \t" + minNumber + "index: " + minNumberIndex);
console.log(maxNumber - minNumber);  

请帮忙!

11 个答案:

答案 0 :(得分:4)

let MaxDifference = arr => {
  let maxDiff = null;
  for(let x = 0; x < arr.length; x++){
    for(let y = x+1; y < arr.length; y++){
        if(arr[x] < arr[y] && maxDiff < (arr[y] - arr[x])){
            maxDiff = arr[y] - arr[x]
        }
    }
  }
  return maxDiff === null ? -1 : maxDiff;
}

答案 1 :(得分:2)

O(n)解决方案:

function maxDifference(arr) {
  let maxDiff = -1;
  let min = arr[0];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > min && maxDiff < arr[i] - min) {
      maxDiff = arr[i] - min;
    }

    if (arr[i] < min) {
      min = arr[i];
    }
  }
  return maxDiff;
}

console.log(maxDifference([1, 2, 3])); //2
console.log(maxDifference(3, 2, 1)); //-1
console.log(maxDifference([2, 3, 10, 2, 4, 8, 1])); //8
console.log(maxDifference([7, 9, 5, 6, 3, 2])); //2
console.log(maxDifference([22, 2, 4, 5, 6, 444, 1, 666])); //665
console.log(maxDifference([7, 9, 5, 6, 3, 2])); //2
console.log(maxDifference([666, 555, 444, 33, 22, 23])); //1
console.log(maxDifference([2, 3, 10, 2, 4, 8, 1])); //8

答案 2 :(得分:1)

您可以拥有两个阵列。让我们称他们为minlrmaxrl

minlr - minlr[i]在原始数组中从左到右存储索引i时的最小值。

maxrl - maxrl[i]在原始数组中从右向左存储指数i之前的最大值。

一旦有了这两个数组,就会迭代数组,找出maxrl[i]minlr[i]之间的最大差异。

在上面的示例中:

  1. minlr = {2,2,2,2,2,2,1};

    maxrl = {10,10,10,8,8,8,1};

    所以这个案例的答案是10 - 2 = 8。

  2. minlr = {7,7,5,5,3,2};

    maxrl = {9,9,6,6,3,2};

    所以这个案例的答案是9 - 7 = 2

答案 3 :(得分:1)

es6版本:

var a = [2, 3, 10, 2, 4, 8, 1];
var min = a[0];
var max = a[a.length-1];
var init = [[0,min], [a.length -1,max]];



var r = a.reduce((
            res, e,i
        )=>{
    var [[mini, min ], [maxi ,max]] = res;
    var t = res;
    if(e<min && i<maxi){
        t = [[i, e ], [maxi ,max]];
    }
    if(e>=max && i>mini){
       t = [[mini, min ], [i ,e]];
    }
    return t;
}, init);
console.log(r[1][1]-r[0][1]);

答案 4 :(得分:1)

我们可以使用es6 + es2020最新功能来解决此问题

function maxDiff(arr) {
 
 var diff=0
 if(arr?.length) diff=arr?.length?Math.max(...arr)-Math.min(...arr):0
 
  return diff;
}

console.log(maxDiff([1, 2, 3])); //2
console.log(maxDiff([3, 2, 1])); //2
console.log(maxDiff([2, 3, 10, 2, 4, 8, 1])); //9
console.log(maxDiff([7, 9, 5, 6, 3, 2])); //7
console.log(maxDiff([22, 2, 4, 5, 6, 444, 1, 666])); //665
console.log(maxDiff([7, 9, 5, 6, 3, 2])); //7
console.log(maxDiff([666, 555, 444, 33, 22, 23])); //644
console.log(maxDiff([-0, 1, 2, -3, 4, 5, -6])); //11
console.log(maxDiff([2])); //0
console.log(maxDiff([])); //0

答案 5 :(得分:0)

你实际上并不需要任何循环,只需使用Math.max(),Math.min()和[] .indexOf()来为你做繁重的工作:

function findDiff(a){  
  var max=Math.max.apply(0, a),
    slot=a.lastIndexOf(max),
    min=Math.min.apply(0, a.slice(0, slot));
  if(a.length && !slot && !min-.153479 )return findDiff(a.slice(1));
  return max-min;
}

//ex: findDiff([7, 9, 5, 6, 3, 2]) == 2
//ex: findDiff([666, 555, 444 , 33, 22, 23]) == 1
//ex: findDiff([2, 3, 10, 2, 4, 8, 1]) == 8

答案 6 :(得分:0)

这可以吗?对于数组中的每个项目,它会查看前面的项目,并将差异添加到内部的差异中。数组(如果当前项更大)。然后我返回diffs数组中的最大值。

var findMaxDiff = function(arr){
    var diffs = [];
    for(var i = 1; i < arr.length; i++){
        for(var j = 0; j < i; j++){
            if(arr[i] > arr[j]){
                diffs.push(arr[i]-arr[j]);
            }
        }
    }
    return Math.max.apply( Math, diffs );
}

答案 7 :(得分:0)

循环遍历数组并使用递归,如下所示:

function maxDifference(a){  
 var maxDiff = a[1] - a[0];  
  for(var i = 2; i<a.length-1; i++){
      var diff = a[i] - a[0];
      maxDiff = diff>maxDiff ? diff : maxDiff;
  }  
  if(a.length>1){
      a.shift();    
      var diff = maxDifference(a);
      maxDiff = diff>maxDiff ? diff : maxDiff;
  }

  return maxDiff;
}
        var x = [2, 3, 10, 2, 4, 8, 1];
        maxDifference(x); // returns 8
        x = [7, 9, 5, 6, 3, 2];
    maxDifference(x) // returns 2

答案 8 :(得分:0)

在线性时间和恒定记忆中:

function maxDiff (nums) {
  var diff = 0, left = 0, right = 0, cur_right = 0, cur_left = 0;
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] < nums[cur_left]) {
      cur_left = i;
      if (cur_left > cur_right) {
        cur_right = cur_left;
      }
    }
    if (nums[i] >= nums[cur_right]) {
      cur_right = i;
    }
    if (nums[cur_right] - nums[cur_left] > diff) {
      diff = nums[cur_right] - nums[cur_left];
      right = cur_right;
      left = cur_left;
    }
  }
  return [diff, left, right];
}

如果您只对差异感兴趣而不感兴趣,那么您就不需要leftright

答案 9 :(得分:0)

&#13;
&#13;
maxdiff = 0;
a =  [2, 3, 10, 2, 4, 8, 1]
for (i=a.length-1; i >= 0; i--) {
  for (j=i-1; j >= 0; j--) {
    if (a[i] < a[j] ) continue;
    if (a[i] -a[j] > maxdiff) maxdiff = a[i] -a[j]
  }
}
console.log(maxdiff || 'No difference found')
&#13;
&#13;
&#13;

答案 10 :(得分:0)

EcmaScript 2017

const array = [1, 2, 40, 4, 20];

const maxDifference = array =>
  array.reduce(
    (acc, number, index, array) =>
      acc > number - array[index - 1] ? acc : number - array[index - 1],
    0,
  );