fork download
  1. using System;
  2.  
  3. public class Program
  4. {
  5. // Step through this C# implementation with the same input on Algo.pw:
  6. // https://a...content-available-to-author-only...o.pw/kadane?ui=en#lang=csharp&numbers=-2,3,-5,4,-1,3,-2&mode=run&step=1
  7. static int MaxSubarray(int[] numbers) {
  8. int size = numbers.Length;
  9. int i = 0;
  10. int total = 0;
  11. int best = 0;
  12. while (i < size) {
  13. if (total < 0) {
  14. total = 0;
  15. }
  16. total = total + numbers[i];
  17. if (i == 0 || total > best) {
  18. best = total;
  19. }
  20. i = i + 1;
  21. }
  22. return best;
  23. }
  24.  
  25. public static void Main()
  26. {
  27. int[][] examples = {
  28. new[] { -2, 3, -5, 4, -1, 3, -2 },
  29. new[] { -8, -2, -5 },
  30. Array.Empty<int>()
  31. };
  32. foreach (int[] numbers in examples)
  33. {
  34. Console.WriteLine($"[{string.Join(", ", numbers)}] => {MaxSubarray(numbers)}");
  35. }
  36. }
  37. }
Success #stdin #stdout 0.13s 5976KB
stdin
Standard input is empty
stdout
[-2, 3, -5, 4, -1, 3, -2] => 6
[-8, -2, -5] => -2
[] => 0