MCPcopy Create free account
hub / github.com/algorithmzuo/videocode / Code02_MaxLeftMaxRight

Class Code02_MaxLeftMaxRight

src/videocode/Code02_MaxLeftMaxRight.java:3–99  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package videocode;
2
3public class Code02_MaxLeftMaxRight {
4
5 // 笨办法,但是好想
6 public static int solution1(int[] arr) {
7 if (arr == null || arr.length < 2) {
8 return 0;
9 }
10 int N = arr.length;
11 int ans = Integer.MIN_VALUE;
12 // 0...0 左 1...N-1
13 // 0...1 左 2...N-1 右
14 // 0...2 左 3...N-1 右
15 // 0...LeftEnd 左 leftEnd+1..N-1 右
16 // 0...N-1 右无
17 for (int leftEnd = 0; leftEnd < N - 1; leftEnd++) {
18 int leftMax = arr[0];
19 for (int i = 1; i <= leftEnd; i++) {
20 leftMax = Math.max(leftMax, arr[i]);
21 }
22 int rightMax = arr[leftEnd + 1];
23 for (int i = leftEnd + 2; i < N; i++) {
24 rightMax = Math.max(rightMax, arr[i]);
25 }
26 ans = Math.max(ans, Math.abs(leftMax - rightMax));
27 }
28 return ans;
29 }
30
31 // 好办法,是我们真正想测试的
32 public static int solution2(int[] arr) {
33 if (arr == null || arr.length < 2) {
34 return 0;
35 }
36 int N = arr.length;
37 int max = arr[0];
38 for (int i = 1; i < N; i++) {
39 max = Math.max(max, arr[i]);
40 }
41 return max - Math.min(arr[0], arr[N - 1]);
42 }
43
44 // 生成随机数组arr
45 // arr的长度也是随机决定的,为[0, maxLen]范围
46 // arr的每个值也是随机决定的,为[-maxValue, +maxValue]范围
47 // 最终返回arr
48 public static int[] randomArray(int maxLen, int maxValue) {
49 // Math.random() -> [O,1) 小数 等概率返回
50 // Math.random() * N -> [0,N) 小数 等概率返回
51 // (int)(Math.random() * N) -> [0,N-1] 整数 等概率返回
52 // (int)(Math.random() * (N + 1)) -> [0,N] 整数 等概率返回
53 // len -> [0, maxLen] 整数,等概率
54 int len = (int) (Math.random() * (maxLen + 1));
55 int[] arr = new int[len];
56 for (int i = 0; i < arr.length; i++) {
57 // arr[i] [-maxValue, +maxValue]
58 arr[i] =
59 (int) (Math.random() * (maxValue + 1)) // [0, maxValue]
60 -

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected