繁体   English   中英

找到可能的最大总和

[英]Find maximum sum possible

通过将数组中的数字相加来找到可能的最大和。 您可以添加任意数量的数字,但不能跳过数字。

  {1, 2, 3, -4, 3} max sum is 6 (1 2 and 3)
  {1, 2, 3, -4, 3, 2, -3, 2} max sum is 7 (1 2 3 -4 3 and 2)
  {1, 2, 4} max sum is 7
  {-4, -3, -10, -12} max sum is -3

您可以假设最小值为 -10000

public int maximumSum( int[] a ) {
      return max;
  }

可能是这样的;

public int getMaxSum(int[] numbers)
{
   //this stores the highest sum we have found so far
   //Integer.MIN_VALUE is the smallest possible value,
   //but your assignment would work with maxSum = -10000;
   int maxSum = Integer.MIN_VALUE;

   //starting at the 1st number in the list, then the 2nd, etc
   for (int pos = 0; pos < numbers.length; pos++)
   {

      //will temporarily hold the sum of numbers from "pos" onwards
      int val = 0;

      //take the number at "pos + 0", then "pos + 1", etc
      for (n = 0; n< numbers.length - pos; n++)
      {
         //add the next number to the current tally
         val += numbers[pos + n];

         //if it is bigger, then we have a new highest sum
         if (val > maxSum) maxSum = val;

      }
   }

   //now maxSum should hold the highest sum
   return maxSum;
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM