Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             var randomizer = new Random();
  6.  
  7.             int[] checkArray;
  8.  
  9.             int expected, actual;
  10.  
  11.             bool isSumCorrect = true;
  12.  
  13.             while (isSumCorrect)
  14.             {
  15.                 checkArray = new int[randomizer.Next(1, 100)];
  16.  
  17.                 for (int i = 0; i < checkArray.Length; i++)
  18.                 {
  19.                     checkArray[i] = randomizer.Next(-100, 100);
  20.                 }
  21.  
  22.                 expected = OptimalSummator.Check(checkArray);
  23.  
  24.                 actual = NonOptimalSummator.Check(checkArray);
  25.  
  26.                 isSumCorrect = expected == actual;
  27.             }
  28.         }
  29.     }
  30.  
  31.     static class OptimalSummator
  32.     {
  33.         public static int Check(int[] arr)
  34.         {
  35.             int local, global, current;
  36.  
  37.             local = global = current = arr[0];
  38.  
  39.             for (int i = 1; i < arr.Length; i++)
  40.             {
  41.                 current = arr[i];
  42.  
  43.                 if (local >= 0)
  44.                 {
  45.                     local = Math.Max(0, Math.Max(current, local + current));
  46.                 }
  47.                 else
  48.                 {
  49.                     local = Math.Max(local, current);
  50.                 }
  51.  
  52.                 global = Math.Max(local, global);
  53.             }
  54.  
  55.             return global;
  56.         }
  57.     }
  58.  
  59.     static class NonOptimalSummator
  60.     {
  61.         public static int Check(int[] arr)
  62.         {
  63.             int global = arr[0];
  64.             int local;
  65.  
  66.             for(int i = 0; i < arr.Length; i++)
  67.             {
  68.                 local = 0;
  69.  
  70.                 for(int j = i; j < arr.Length; j++)
  71.                 {
  72.                     local += arr[j];
  73.  
  74.                     global = Math.Max(global, local);
  75.                 }
  76.             }
  77.  
  78.             return global;
  79.         }
  80.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement