ellapt

T7.6.MaxSumKElems

Jan 15th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. using System;
  2.  
  3. class MaxSumKElems
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. uint n, k;
  9. int workSum = 0;
  10. int maxSum = 0; // the resulting max sum of k consecutive elements
  11. int maxStart = 0; // the start index of the max sum sequence of k consecutive elements
  12. Console.WriteLine("Find k consecutive elements with max sum in an array");
  13. do
  14. {
  15. Console.Write("Enter array length: ");
  16. }
  17. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  18. do
  19. {
  20. Console.Write("Enter subset length: ");
  21. }
  22. while (!(uint.TryParse(inputVar = Console.ReadLine(), out k)) || k == 0);
  23.  
  24. int[] arrayOfints = new int[n];
  25.  
  26. Console.WriteLine("Now enter the elements of the array:");
  27. for (int i = 0; i < n; i++)
  28. {
  29. arrayOfints[i] = int.Parse(Console.ReadLine());
  30. }
  31. for (int i = 0; i < n - k + 1; i++)
  32. {
  33. for (int j = i; j < i+k; j++)
  34. {
  35. workSum += arrayOfints[j];
  36. }
  37. if (workSum > maxSum)
  38. {
  39. maxSum = workSum;
  40. maxStart = i;
  41. workSum = 0;
  42. }
  43. else
  44. {
  45. workSum = 0;
  46. }
  47. }
  48. Console.WriteLine("The sequence of {0} consecutive elements with max sum:", k);
  49. for (int i = maxStart; i < maxStart+k-1; i++)
  50. {
  51. Console.Write("{0} + ", arrayOfints[i]);
  52. }
  53. Console.WriteLine("{0} = {1}", arrayOfints[maxStart + k - 1], maxSum);
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment