• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# C# 2 Array Problem8

LERRY Dec 22nd, 2013 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /* Write a program that finds the sequence of maximal sum in given array.
2.  * Example:
3.  * {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} -> {2, -1, 6, 4}
4.  * Can you do it with only one loop (with single scan through the elements of the array)?
5.  */
6.
7. namespace _08_01_SequenceWithMaxSum
8. {
9.     using System;
10.     class SequenceWithMaxSum
11.     {
12.         static void Main()
13.         {
14.             Console.WriteLine("Please, insert the length of the array:");
16.             Console.WriteLine("Please, insert the elements of the array:");
17.             int[] array = new int[n];
18.             for (int i = 0; i < n; i++)
19.             {
21.             }
22.
23.             int maxSum = 0;
24.             int currentSum = 0;
25.             int startPosition = 0;
26.
27.             for (int i = 0; i < n; i++)
28.             {
29.                 for (int j = i; j < n; j++)
30.                 {
31.                     currentSum += array[j];
32.                 }
33.                 if (currentSum > maxSum)
34.                 {
35.                     maxSum = currentSum;
36.                     startPosition = i;
37.                 }
38.                 currentSum = 0;
39.             }
40.             Console.WriteLine("The max sum of consecutive elements = {0}", maxSum);
41.             Console.WriteLine("The consecutive elements with max sum are:");
42.             currentSum = 0;
43.             while (currentSum < maxSum)
44.                 {
45.                 Console.WriteLine(array[startPosition]);
46.                 currentSum += array[startPosition];
47.                 startPosition++;
48.                 }
49.         }
50.     }
51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top