简体   繁体   English

算法的复杂度和效率:a [j] -a [i] i> = j

[英]Complexity and Efficiency in Algorithm for: a[j]-a[i] i>=j

I'm looking to make this much quicker. 我正在寻求更快的速度。 I've contemplated using a tree, but I'm not sure if that would actually help much. 我已经考虑过使用一棵树,但是我不确定这是否真的有很大帮助。

I feel like the problem is for most cases you don't need to calculate all the possible maximums only a hand full, but I'm not sure where to draw the line 我觉得问题在于,在大多数情况下,您只需要满手就不需要计算所有可能的最大值,但是我不确定在哪里画线

Thanks so much for the input, Jasper 非常感谢Jasper的投入

public class SpecialMax {

    //initialized to the lowest possible value of j; 
    public static int jdex = 0; 
    //initialized to the highest possible value of i; 
    public static int idex; 
    //will hold possible maximums 
    public static Stack<Integer> possibleMaxs = new Stack<Integer> (); 

    public static int calculate (int[] a){
        if (isPositive(a)){ 
            int size = a.length; 
            int counterJ; 
            counterJ = size-1;

            //find and return an ordered version of a

            int [] ordered = orderBySize (a);

            while (counterJ>0){
                /* The first time this function is called, the Jvalue will be 
                 * the largest it can be, similarly, the Ivalue that is found
                 * is the smallest
                 */
                int jVal  = ordered[counterJ];  
                int iVal  = test (a, jVal);
                possibleMaxs.push(jVal-iVal);
                counterJ--; 
            }

            int answer = possibleMaxs.pop(); 

            while (!possibleMaxs.empty()){
                if (answer<possibleMaxs.peek()){
                    answer = possibleMaxs.pop(); 
                } else { 
                    possibleMaxs.pop(); 
                }
            }

            System.out.println("The maximum of a[j]-a[i] with j>=i is: ");
            return answer;
        } else {
            System.out.println ("Invalid input, array must be positive"); 
            return 0; //error
        }
    }

    //Check to make sure the array contains positive numbers
    public static boolean isPositive(int[] a){ 
        boolean positive = true; 
        int size = a.length; 

        for (int i=0; i<size; i++){
            if (a[i]<0){
                positive = false; 
                break; 
            }
        }


        return positive; 
    }

    public static int[] orderBySize (int[] a){
         //orders the array into ascending order
         int [] answer = a.clone(); 
         Arrays.sort(answer);
         return answer; 
    }

         /*Test returns an Ival to match the input Jval it accounts for 
          * the fact that jdex<idex. 
          */
    public static int test (int[] a, int jVal){
        int size = a.length;
        //initialized to highest possible value
        int tempMin = jVal; 
        //keeps a running tally 
        Stack<Integer> mIndices = new Stack<Integer> (); 

        //finds the index of the jVal being tested
        for (int i=0; i<size; i++) { 
            if (jVal==a[i]){
                //finds the highest index for instance
                if (jdex<i){
                    jdex = i;
                }
            }
        }

        //look for the optimal minimal below jdex;  
        for (int i=0; i<jdex; i++){
            if (a[i]<tempMin){
                tempMin = a[i]; 
                mIndices.push(i);
            }
        }

        //returns the index of the last min
        if (!mIndices.empty()){
           idex = mIndices.pop(); 
        }

        return tempMin; 
    }

}

It can be done in linear time and linear memory. 可以在线性时间和线性存储器中完成。 The idea is: find the minimum over each suffix of the array and maximum over each prefix, then find the point where the difference between the two is the highest. 这个想法是:在数组的每个后缀中找到最小值,在每个前缀中找到最大值,然后找到两者之差最大的点。 You'll also have to store the index on which the maximum/minimum for each prefix is reached if you need the indices, rather than just the difference value. 如果需要索引,您还必须存储索引,在该索引上可以达到每个前缀的最大值/最小值,而不仅仅是差异值。

Pre-sorting a[] makes the procedure complicated and impairs performance. 对a []进行预排序会使过程变得复杂并降低性能。 It is not necessary, so we leave a[] unsorted. 不必要,所以我们将a []未排序。

Then (EDITED, because I had read j>=i in the body of your code, rather than i>=j in the problem description/title, which I now assume is what is required (I didn't go over your coding details); The two varieties can easily be derived from each other anyway.) 然后(编辑,因为我在代码正文中读了j> = i,而不是问题描述/标题中的i> = j,我现在假设这是必需的(我没有遍历您的编码详细信息);无论如何,这两个变体可以很容易地彼此衍生。

// initialize result(indices)
int iFound = 0;
int jFound = 0;
// initialize a candidate that MAY replace jFound
int jAlternative = -1; // -1 signals: no candidate currently available

// process the (remaining) elements of the array - skip #0: we've already handled that one at the initialization
for (int i=1; i<size; i++)
{
  // if we have an alternative, see if that combines with the current element to a higher "max".
  if ((jAlternative != -1)  && (a[jAlternative]-a[i] > a[jFound]-a[iFound]))
  {
    jFound = jAlternative;
    iFound = i;
    jAlternative = -1;
  }
  else if (a[i] < a[iFound]) // then we can set a[iFound] lower, thereby increasing "max"
  {
    iFound = i;
  }
  else if (a[i] > a[jFound])
  { // we cannot directly replace jFound, because of the condition iFound>=jFound,
    // but when we later may find a lower a[i], then it can jump in:
    // set it as a waiting candidate (replacing an existing one if the new one is more promising).
    if ((jAlternative = -1) || (a[i] > a[jAlternative]))
    {
      jAlternative = i;
    }
  }
}

double result = a[jFound] - a[iFound];

找到对 (i,j) 使得 i <j and (a[i] + a[j]) is maximum< div><div id="text_translate"><p> 给定一个未排序的数组——找到一对 arr[i] 和 arr[j] 使得arr[i] &lt; arr[j] &amp; i&lt;j并且(arr[i] + arr[j])是最大的。</p><p> 预期时间复杂度 - O(n)</p><p> 对于数组a = {4, 1, 3, 2, 5, 3}</p><pre> pair is (4, 5).</pre><p> 这是我试过的代码..</p><pre> void findPair(int[] a){ int n = a.length; int max = a[0]; int secondMax = Integer.MIN_VALUE; for(int i=1; i&lt;n; i++){ if(a[i]&gt;max){ secondMax = max; max = a[i]; } } if(secondMax == Integer.MIN_VALUE){ System.out.println("-1 -1"); } else{ System.out.println(secondMax+" "+max); } }</pre></div></j> - Find the pair (i,j) such that i<j and and (a[i] + a[j]) is maximum

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 j 收缩为 j = (j - 1) &amp; i 的循环的复杂性 - Complexity of a loop where j shrinks as j = (j - 1) & i 为什么(i <= j && j <= i && i!= j)评估为TRUE? - Why does (i<=j && j<=i && i!=j) evaluate to TRUE? 找到对 (i,j) 使得 i <j and (a[i] + a[j]) is maximum< div><div id="text_translate"><p> 给定一个未排序的数组——找到一对 arr[i] 和 arr[j] 使得arr[i] &lt; arr[j] &amp; i&lt;j并且(arr[i] + arr[j])是最大的。</p><p> 预期时间复杂度 - O(n)</p><p> 对于数组a = {4, 1, 3, 2, 5, 3}</p><pre> pair is (4, 5).</pre><p> 这是我试过的代码..</p><pre> void findPair(int[] a){ int n = a.length; int max = a[0]; int secondMax = Integer.MIN_VALUE; for(int i=1; i&lt;n; i++){ if(a[i]&gt;max){ secondMax = max; max = a[i]; } } if(secondMax == Integer.MIN_VALUE){ System.out.println("-1 -1"); } else{ System.out.println(secondMax+" "+max); } }</pre></div></j> - Find the pair (i,j) such that i<j and and (a[i] + a[j]) is maximum 循环i和j,其中i!= j - Loop i and j, where i != j j = i + 1 和 j = ++i 之间的差异; - Difference between j = i + 1 and j = ++i; 算法复杂度和效率,指数运算java - Algorithm Complexity and Efficiency, Exponential operation java 查找数组中A [i] * A [j]&gt; A [i] + A [j]的对数 - Finding number of pairs in array where A[i] * A[j] > A[i] + A[j] 找到A的最大值[J] + - A [I] - Finding Max Value Of A[J] +- A[I] Java不是i <j的语句错误 - Java not a statement error at i < j 如何在WSS4J 2.2.3中启用RSA15传输算法? - How can I enable RSA15 transport algorithm in WSS4J 2.2.3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM