Inventory Item
PHP
Medium
8 views
Problem Description
Create Item with qty. Commands: ADD x, SELL x (cannot go below 0). Print final qty.
Input Format
First line q. Next q lines.
Output Format
One integer qty.
Sample Test Case
Input:
5
ADD 10
SELL 3
SELL 20
ADD 5
SELL 2
Official Solution
<?php
class Item{
private $qty=0;
function add($x){ $this->qty += $x; }
function sell($x){ if($this->qty >= $x) $this->qty -= $x; }
function qty(){ return $this->qty; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$item=new Item();
for($i=1;$i<=$q;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2);
$cmd=$tokens[0] ?? '';
$x=intval($tokens[1] ?? 0);
if($cmd==='ADD') $item->add($x);
elseif($cmd==='SELL') $item->sell($x);
}
echo $item->qty();
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!