无序数组array, 找到数组中两个数的最大差值

题目链接:

无序数组array, 找到数组中两个数的最大差值, 且大数出现在小数之后,如:arr[i]-arr[j], 且 i<j。比如: array 是 [2, 3, 10, 6, 4, 8, 1],最大差值是8(10-2)

解题思路:

记录当前访问过的数组中的最小值 min_val;

2) 当前元素值arr[i] - min_val 和 max_diff作比较

若大于 max_diff , 则更新它的值

 1 import javax.validation.constraints.Min;
 2 
 3 
 4 public class Maxarea {
 5     
 6 
 7     public static int maxArea(int[] height) {
 8         
 9         int max_diff = Integer.MIN_VALUE;
10         int min = Integer.MAX_VALUE;
11         for(int i=0;i<height.length;i++)
12         {
13             if(height[i]<min)//事先设置min为最大的值,如果遇到一个比min还小的,就存下来,最后一个数就是最小的数
14             {
15                 min = height[i];
16             }
17             
18             if(max_diff<(height[i]-min))//事先设置max为最小的值,如果找到一个比他还大的就存下来,最后一个数就是最大的数
19             {
20                 max_diff = height[i]-min;
21             }
22             
23         }
24         
25         return max_diff;
26         
27     }
28     
29     public static void main(String[] args) {
30         int []a ={2, 3, 10, 6, 4, 8, 1};
31         
32         System.out.println(maxArea(a));
33     }
34 }

猜你喜欢

转载自www.cnblogs.com/wangyufeiaichiyu/p/10896202.html