Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class MaxIncreasingSequenceInArray
- {
- static void Main()
- {
- //Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} -> {2, 3, 4}.
- int[] myArray = { 42, 41, 20, 12, 3, 4 };
- int counter = 1,
- maxCounter = 1,
- maxElement = myArray[0]; //In case of just one element in the array the first element is the winner, that's why the initial value is the one of the first element.
- int element = myArray[0]; //The element we compare with. It's the first element of the array with index 0.
- //Find the maximal sequence of equal elements in the array
- for (int i = 1; i < myArray.Length; i++) //The cycle starts the comparison from the second memeber of the sequence with index 1.
- {
- if (myArray[i] == element+1)
- {
- counter++;
- element = myArray[i];
- if (counter > maxCounter)//Note! If there are 2 or more sequences of equal lenghts by checking with ">" the output will be the first sequence. If we check with ">=" we'll get the last one.
- {
- maxCounter = counter;
- maxElement = myArray[i];
- }
- }
- else
- {
- counter = 1;
- element = myArray[i];
- }
- }
- //Generate the output string, e.g. 2,2,2
- string output = "";
- for (int j = 1; j <= maxCounter; j++)
- {
- if (j != maxCounter)
- {
- output += ((maxElement - maxCounter) + j) + ", ";
- }
- else
- {
- output += ((maxElement - maxCounter) + j);
- }
- }
- //Print the output string on the console with the correct formatting, e.g. {2,2,2}
- Console.Write("{");
- Console.Write("{0}", output);
- Console.WriteLine("}");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement