在一个数组中找差值最大数对,输出最大差值

题目:一个数组,找一个数对,使得两个数对之差最大,并且较大数在较小数之前,要求时间复杂度为O(n)

解决方法:

动态规划,额外定义两个数组,temp[]、max[]

temp[i]用来存储,从开始到下标为i的元素位置,最大数对之差

max[i]用来存储,从开始到下标为i的元素位置,最大值

i=0时:

temp[i]=0;

max[i]=A[i];

i!=0时:

temp[i+1]=max{temp[i],max[i]-A[i+1]};

max[i+1]=max{max[i],A[i+1]};

实现代码如下:

[java]  view plain  copy
  1. public class Test{  
  2.     public static int []temp;  
  3.     public static int []max;  
  4.     public static void main(String []args){  
  5.         int []A ={1,2,-1,6,8,3,5,2,6};  
  6.         temp=new int [A.length];  
  7.         max=new int [A.length];  
  8.         System.out.println(find(A));  
  9.     }  
  10.     public static int find(int []A){  
  11.         int i;  
  12.         for(i=0;i<A.length;i++){  
  13.             if(i==0){  
  14.                 temp[i]=0;  
  15.                 max[i]=A[i];  
  16.             }else{  
  17.                 temp[i]=maxtwo(temp[i-1],max[i-1]-A[i]);  
  18.                 max[i]=maxtwo(max[i-1],A[i]);  
  19.             }  
  20.         }  
  21.         return temp[i-1];  
  22.     }  
  23.     public static int maxtwo(int a,int b){//返回二者最大值  
  24.         if(a>b){  
  25.             return a;  
  26.         }else{  
  27.             return b;  
  28.         }  
  29.     }  
  30. }  

时间复杂度为:O(n)

空间复杂度为:O(n)

转载:https://blog.csdn.net/abbcbbd/article/details/51464699

猜你喜欢

转载自blog.csdn.net/dongyu_1989/article/details/80755018