算法寻找最大乘积 – 分析

huangapple go评论67阅读模式
英文:

Algorithm that finds the maximum product - Analysis

问题

我有这段代码它在数组中计算出使用3个数字可以找到的最大乘积

    public static int findMaxProduct(int[] arr) {

    		int i=0, j=1, f=2;
    		
    		int largest = arr[i]*arr[j]*arr[f];
    		for(;i<arr.length;) {
    			if(largest<arr[i]*arr[j]*arr[f])
    				largest = arr[i]*arr[j]*arr[f];
    
    			if(i==arr.length-3)
    				return largest;
    			
    			if(f==arr.length-1 && j == arr.length - 2) {
    				i++;
    				j=i+1;
    			}
    			if( f==arr.length-1 && j != arr.length-2) 
    				f = j+1;
    			
    			if(f<arr.length-1)
    				f++;
    			if(f==arr.length -1 && j < arr.length -2)
    				j++;
    				
    			
    			
    			
    		}
    		return 0;
    	}

现在我不确定它的复杂度是什么因为我们只有在满足条件时才会增加i”,而且我们不知道何时会执行i++”。如果您能帮助我找出复杂度我将不胜感激!(时间
英文:

I have this code which is calculating the largest product you can find using 3 numbers in an array:

public static int findMaxProduct(int[] arr) {

		int i=0, j=1, f=2;
		
		int largest = arr[i]*arr[j]*arr[f];
		for(;i&lt;arr.length;) {
			if(largest&lt;arr[i]*arr[j]*arr[f])
				largest = arr[i]*arr[j]*arr[f];

			if(i==arr.length-3)
				return largest;
			
			if(f==arr.length-1 &amp;&amp; j == arr.length - 2) {
				i++;
				j=i+1;
			}
			if( f==arr.length-1 &amp;&amp; j != arr.length-2) 
				f = j+1;
			
			if(f&lt;arr.length-1)
				f++;
			if(f==arr.length -1 &amp;&amp; j &lt; arr.length -2)
				j++;
				
			
			
			
		}
		return 0;
	}

Now, I am not sure of what complexity it is, as we increment i if only a condition is met, and we don't know where it's going to execute i++ . I would appreciate if you help me find the complexity! (Time)

答案1

得分: 2

你测试所有的三元组。大约有 n^3 个。因此复杂度是 O(n^3)

英文:

You test all the triplets. There are about n^3 of them. Therefore the complexity is O(n^3).

huangapple
  • 本文由 发表于 2020年5月4日 04:55:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61581492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定