Algorithm-Arrays-4 最大绝对距离Max Absolute Difference
来源:互联网 发布:泰安网络推广 编辑:程序博客网 时间:2024/06/03 20:14
1. 问题描述
You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N.
f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.
For example,
A=[1, 3, -1]
f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5
So, we return 5.
求一个数组中的最大曼哈顿距离,要求时间复杂度为O(n).
曼哈顿距离定义:The distance between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 - x2| + |y1 - y2|.
2. 复杂度为O(n^2)的算法
public int maxArr1(ArrayList<Integer> A) { int result, temp; result = 0; for (int i = 0; i < A.size(); i++) { for (int j = i + 1; j < A.size(); j++) { temp = Math.abs(A.get(j) - A.get(i)) + Math.abs(j - i); if (result < temp) result = temp; } } return result; }
3. 复杂度为O(n)算法
算法思路:
1). 在数组中找到以下的点:max(x[i]+y[i]), max(x[I]-y[I]),max(-x[i]+y[I]),max(-x[I]-y[I]).
2). 计算数组中的每个点的上述距离,并取最大的值。该算法以线性时间运行,因为只考虑4*N对点。
3). 我们可以首先固定一个点,如(x[k],y[k]), 并找到离该点最远的一个点。考虑任意的点(x[i], y[i]), 则按曼哈顿距离展开后,假设展开后为如下情形可知道:
x[I]+x[k]+y[I]+y[k] = (x[k]+y[k]) + x[I]+y[I];
其中第一部分为固定的,所以最大值即为后一部分的值。其他的三种情形亦然。
public int maxArr(ArrayList<Integer> A) { int sz = A.size(); int max1 = Integer.MIN_VALUE; int max2 = Integer.MIN_VALUE; int max3 = Integer.MIN_VALUE; int max4 = Integer.MIN_VALUE; int ans = Integer.MIN_VALUE; for (int i = 0; i < sz; i++) { max1 = Math.max(max1, A.get(i) + i); max2 = Math.max(max2, -A.get(i) + i); max3 = Math.max(max3, A.get(i) - i); max4 = Math.max(max4, -A.get(i) - i); } for (int i = 0; i < sz; i++) { ans = Math.max(ans, max1 - A.get(i) - i); ans = Math.max(ans, max2 + A.get(i) - i); ans = Math.max(ans, max3 - A.get(i) + i); ans = Math.max(ans, max4 + A.get(i) + i); } return ans; }
- Algorithm-Arrays-4 最大绝对距离Max Absolute Difference
- Algorithm Arrays-3 Max Sum Contiguous Subarray
- [LeetCode]530. Minimum Absolute Difference in BST(BST的最小绝对差)
- 最大最小公平共享算法 Max-min Fair Share Algorithm
- 624. Maximum Distance in Arrays 数组最大距离
- 绝对定位Position:absolute
- absolute绝对定位
- 最大最小距离算法(Max-Min-diatance)
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- 绝对最大额定值(ABSOLUTE MAXIMUM RATINGS: ABS)是否可以超过
- Algorithm-Arrays-1
- matlab在图片上分块(在图片上画网格)
- Android 慕课学习笔记整理(一)
- java-static关键字
- IO五种模型(阻塞IO、非阻塞IO、多路复用IO、信号驱动IO、异步IO)
- 除了打通各类知识平台的激励系统,他们还想做国际领先的区块链技术社区
- Algorithm-Arrays-4 最大绝对距离Max Absolute Difference
- 通过jquery的animate实现可以左右点击的轮播
- 自定义进度条,可在进度条中添加节点
- 简单的静态通讯录的实现。
- 计算字符串最后一个单词的长度,单词以空格隔开
- poj 1182 食物链 【带权并查集】
- Maven学习之插件—maven-assembly-plugin
- 使用多层 LSTM API(4/7)
- git revert