2016-04-17 11 views
-6

配列に数字を追加することで可能な最大限の合計を見つける。あなたは好きなだけ多くの数字を追加できますが、数字をスキップすることはできません。最大合計を見つける

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

宿題はありますか? – Pooya

+1

はい、並べ替えます。それは15分のクイズでした。わかりませんでしたので、今私はそれに取り組んでいます。 – jean

+1

public int maximumSum(int [] a){ int max = -10000; (iは= STをint型用{ ため (INT SZ = 0; SZ <= a.length; SZ ++)(ST ++ = 1番目のint型; ST <= a.length-SZ)のために{ I jean

答えて

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

もっと奨励しているように、あなたはこれらのような悪い質問に答えるべきではありません。 – bcsb1001

関連する問題