算法寻找最大乘积 – 分析

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

Algorithm that finds the maximum product - Analysis

问题

  1. 我有这段代码它在数组中计算出使用3个数字可以找到的最大乘积
  2. public static int findMaxProduct(int[] arr) {
  3. int i=0, j=1, f=2;
  4. int largest = arr[i]*arr[j]*arr[f];
  5. for(;i<arr.length;) {
  6. if(largest<arr[i]*arr[j]*arr[f])
  7. largest = arr[i]*arr[j]*arr[f];
  8. if(i==arr.length-3)
  9. return largest;
  10. if(f==arr.length-1 && j == arr.length - 2) {
  11. i++;
  12. j=i+1;
  13. }
  14. if( f==arr.length-1 && j != arr.length-2)
  15. f = j+1;
  16. if(f<arr.length-1)
  17. f++;
  18. if(f==arr.length -1 && j < arr.length -2)
  19. j++;
  20. }
  21. return 0;
  22. }
  23. 现在我不确定它的复杂度是什么因为我们只有在满足条件时才会增加i”,而且我们不知道何时会执行i++”。如果您能帮助我找出复杂度我将不胜感激!(时间
英文:

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

  1. public static int findMaxProduct(int[] arr) {
  2. int i=0, j=1, f=2;
  3. int largest = arr[i]*arr[j]*arr[f];
  4. for(;i&lt;arr.length;) {
  5. if(largest&lt;arr[i]*arr[j]*arr[f])
  6. largest = arr[i]*arr[j]*arr[f];
  7. if(i==arr.length-3)
  8. return largest;
  9. if(f==arr.length-1 &amp;&amp; j == arr.length - 2) {
  10. i++;
  11. j=i+1;
  12. }
  13. if( f==arr.length-1 &amp;&amp; j != arr.length-2)
  14. f = j+1;
  15. if(f&lt;arr.length-1)
  16. f++;
  17. if(f==arr.length -1 &amp;&amp; j &lt; arr.length -2)
  18. j++;
  19. }
  20. return 0;
  21. }

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:

确定