Bank Balance

Bank Balance

Easy Programming Interview OOP 28 views
Explanation Complexity

Problem Statement

You have a bank account with starting balance B. Then q commands: DEP x, WIT x (withdraw, but if not enough keep same). Output final balance.

Input Format

Line1: B. Line2: q. Next q lines commands.

Output Format

One integer balance.

Example

10
4
DEP 5
WIT 3
WIT 20
DEP 1
13

Constraints

q

Input / Output Format

Input Format
Line1: B. Line2: q. Next q lines commands.
Output Format
One integer balance.
Constraints
q

Examples

Input:
10 4 DEP 5 WIT 3 WIT 20 DEP 1
Output:
13

Example Solution (Public)

Programming Interview
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
B=int(lines[0].strip())
q=int(lines[1].strip())
class Account:
  def __init__(self,b):
    self.b=b
  def dep(self,x):
    self.b+=x
  def wit(self,x):
    if x<=self.b:
      self.b-=x
  def bal(self):
    return self.b
acc=Account(B)
for i in range(q):
  parts=(lines[2+i] if 2+i<len(lines) else '').split()
  if len(parts)<2: continue
  x=int(parts[1])
  if parts[0]=='DEP':
    acc.dep(x)
  else:
    acc.wit(x)
sys.stdout.write(str(acc.bal()))

Official Solution Code

import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
B=int(lines[0].strip())
q=int(lines[1].strip())
class Account:
  def __init__(self,b):
    self.b=b
  def dep(self,x):
    self.b+=x
  def wit(self,x):
    if x<=self.b:
      self.b-=x
  def bal(self):
    return self.b
acc=Account(B)
for i in range(q):
  parts=(lines[2+i] if 2+i<len(lines) else '').split()
  if len(parts)<2: continue
  x=int(parts[1])
  if parts[0]=='DEP':
    acc.dep(x)
  else:
    acc.wit(x)
sys.stdout.write(str(acc.bal()))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.