Friday, December 27, 2013

Sum of consecutive elements in a subsequence

Complete the method to find the minimal length of the sub sequence of consecutive elements of the sequence, sum of which is greater or equal to the specified number.

Example:

 5   1   3   5   10   7   4   9   2   8 

If the specified number is 15 in the sequence
5 + 1 + 3 + 5 + 10 > 15 (length is 5)
1+3+5+10 >= 15 (length is 4)
3+5+10 >= 15 (length is 3)
5 + 10 >= 15 (length is 2)
10 + 7 >=15(length is 2)
There is no element in the array whose value is >= 15 and hence the minimal length is 2
public static int FindMinimalLength(int[] array, int value)
{
        //write code here
}
UTC Sample Input Sample Output
01  array = {5,1,3,5,10,7,4,9,2,8}
value = 15
2
02 array = {1,2,3,4,5}
value = 11
3

SOLUTION: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SumConsecutive
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the length of array : ");
            int i = int.Parse(Console.ReadLine());
            int j = 0;

            int[] arr = new int[i];
            for (j = 0; j < i; j++)
            {
                Console.Write("arr[" + j + "]: ");
                arr[j] = int.Parse(Console.ReadLine());
            }

            //Sorting the array
            Boolean change = false;
            Int32 temp = 0;
            for (i = 0; i < arr.Length; i++)
            {
                for (j = 0; j < arr.Length - 1; j++)
                {
                    if (arr[j] < arr[j + 1])
                    {
                        change = true;
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
                if (!change)
                {
                    break;
                }
            }

            //reading value
            Console.Write("Enter the value: ");
            int value = int.Parse(Console.ReadLine());

            //
            change = true;
            int sum = 0;
            j = 0;
            while (change)
            {
                if (sum + arr[j] > value)
                {
                    change = false;
                }
                else
                {
                    sum += arr[j];
                    j++;
                }
            }
            j++;

            Console.WriteLine("Minimum length: " + j);
        }
    }
}

No comments:

Post a Comment