Skip to content

Instantly share code, notes, and snippets.

@axetroy
Last active August 18, 2020 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/dd6b648040100fcc2b3276eeb40dd608 to your computer and use it in GitHub Desktop.
Save axetroy/dd6b648040100fcc2b3276eeb40dd608 to your computer and use it in GitHub Desktop.
美团2016校招算法题-最大差值
/*
描述:
有一个长度为n的A,满足0<=a<=b<=n的A[b] - A[a]的最大值
给定数组A以及它的大小n,请返回最大差值
example:
[10, 5], 2
返回:0
要点:
b>a: 意味着数组必须是后面的元素,减去前面的
*/
let A = [10, 5, 9, 100];
function maxDiff(arr) {
let diffs = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
diffs = diffs.concat([arr[j] - arr[i]]);
}
}
return Math.max.apply(Math, diffs);
}
maxDiff(A);
// a = 1, b = 3 满足a<b
// A[b] - A[a] = 100 - 5 = 95满足最大差值
@fulgari
Copy link

fulgari commented Aug 18, 2020

请问Math.max.apply()的this指针为什么要指向Math?

@axetroy
Copy link
Author

axetroy commented Aug 18, 2020

请问Math.max.apply()的this指针为什么要指向Math?

没什么特别的,就是用最普通的方法去实现。

当时还没有流行扩展运算符,否则使用 Math.max(...diffs) 会更优雅.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment