From 589c401291a234e315aff6b53ff1d0bfac1182f7 Mon Sep 17 00:00:00 2001 From: vikashkmr3188 <49491177+vikashkmr3188@users.noreply.github.com> Date: Mon, 29 Mar 2021 12:05:14 +0530 Subject: [PATCH] Better Algo --- interview-preparation-kit/counting-valleys.py | 25 ++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/interview-preparation-kit/counting-valleys.py b/interview-preparation-kit/counting-valleys.py index e4ab9f7..7dc7436 100644 --- a/interview-preparation-kit/counting-valleys.py +++ b/interview-preparation-kit/counting-valleys.py @@ -3,23 +3,14 @@ import sys def countingValleys(n, s): - res = 0 - in_valley = 0 - curr = 0 - - for step in s: - if step == 'U': - curr += 1 - else: - curr -= 1 - - if curr < 0 and in_valley == 0: - in_valley = 1 - if in_valley == 1 and curr == 0: - in_valley = 0 - res += 1 - - return res + stepSum=0 + valleyCount=0 + for i in path: + stepSum=stepSum+1 if i=="U" else stepSum + stepSum=stepSum-1 if i=="D" else stepSum + if stepSum==0 and i=="U": + valleyCount=valleyCount+1 + return (valleyCount) if __name__ == "__main__": n = int(input().strip())