MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Inventory Item with Explanation

PHP Medium PHP OOP Basics 46 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around qty, item, line. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

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.

Constraints

q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?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(); ?>

Output Example

Input:
5 ADD 10 SELL 3 SELL 20 ADD 5 SELL 2
Output:
10

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next