Problem Statement: PassingCars
C++ Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // you can use includes, for example: #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A) { // write your code in C++11 (g++ 4.8.2) auto goingEast = 0; auto pairsPassing = 0; for (auto &e : A) { if (e == 0) { goingEast++; } else if (e == 1) { pairsPassing += goingEast; if (pairsPassing > 1000000000) return -1; } } return pairsPassing; } |
C# Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; // you can also use other imports, for example: // using System.Collections.Generic; // you can write to stdout for debugging purposes, e.g. // Console.WriteLine("this is a debug message"); class Solution { public int solution(int[] A) { // write your code in C# 6.0 with .NET 4.5 (Mono) var eastBound = 0; var pairsCrossing = 0; foreach(var car in A) { if(car == 0) { eastBound++; } else if(car == 1) { pairsCrossing += eastBound; if(pairsCrossing > 1000000000) return -1; } } return pairsCrossing; } } |
Learnings
- counting number of 1s or west bound cars
No comments:
Post a Comment