找到可能的最大总和

时间:2016-04-17 06:28:47

标签: java

通过在数组中添加数字来查找可能的最大总和。您可以根据需要添加任意数量的数字,但不能跳过数字。

  {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;
  }

1 个答案:

答案 0 :(得分:0)

可能是这些方面的东西;

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;
}