title: Program to determine total stops taken by elevator
body: <p>I was asked a question to write a optimal program that would determine the total number of stops a elevator has taken to serve X number of people. Question description is as below.</p>
  
  <p>There is a elevator in a building with M floors, this elevator can take a max of X people at a time or max of total weight Y. Given that a set of people has arrived and their weight and the floor they need to stop given how many stops has the elevator taken to serve all the people. Consider elevator serves in the first come first serve basis.</p>
  
  <p>E.g. Let Array A be the weight of people to be considered
  A[] = {60, 80, 40 }</p>
  
  <p>Let Array B be the floors where person needs to be dropped respectively
  B[] = {2, 3, 5}</p>
  
  <p>Total building floors be 5,max allowed person in elevator be 2 at a time with max weight capacity being 200
  For this example the elevator would take total of 5 stops floors ground, 2, 3,ground, 5 , ground</p>
  
  <p>What would be the optimal code for this?</p>
  
  <p>One of my solution is as below. Is there any other better solutions?</p>
  
  <pre><code>class Solution
  {
      /// &lt;summary&gt;
      /// Return total stops used
      /// &lt;/summary&gt;
      /// &lt;param name="A"&gt;weight of people&lt;/param&gt;
      /// &lt;param name="B"&gt;floors they need to get down&lt;/param&gt;
      /// &lt;param name="M"&gt;total floors in the building&lt;/param&gt;
      /// &lt;param name="X"&gt;Max people to carry at a time&lt;/param&gt;
      /// &lt;param name="Y"&gt;max weight to carry at a time&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public int solution(int[] A, int[] B, int M, int X, int Y)
      {
          // write your code in C# 6.0 with .NET 4.5 (Mono)
          int totalStops = 0;
          long totalWeightPerRound = 0;
          int maxPersonsCount = 0;
          List&lt;int&gt; lstFloors = new List&lt;int&gt;();
          int currPerson = 0;
          bool startLift = false;
          while (currPerson &lt; A.Length)
          {
              if ((totalWeightPerRound + A[currPerson]) &lt;= Y &amp;&amp; (maxPersonsCount+1) &lt;= X)
              {
                  totalWeightPerRound += A[currPerson];
                  maxPersonsCount++;
                  lstFloors.Add(B[currPerson]);
                  if (currPerson == A.Length - 1)
                      startLift = true;
  
                  currPerson++;
              }
              else
              {
                  startLift = true;
              }
  
              if (startLift)
              {
                  totalStops += lstFloors.Distinct().Count() + 1;
                  lstFloors.Clear();
                  maxPersonsCount = 0;
                  totalWeightPerRound = 0;
                  startLift = false;
              }
          }
  
          return totalStops;
      }
  }
  </code></pre>