MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

Java Program to Balance tracker with Explanation

Java Medium Variables 23 views
This problem helps you practice core Java fundamentals in a practical way. It builds intuition around balance, negative, transaction. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Task: starting balance and transactions array (+credit, -debit). Return first index where balance becomes negative, else -1.

Input Format

An integer startingBalance
An integer n
Then n integers (transactions: +credit, -debit)

Output Format

Index where balance first becomes negative
If never negative, return -1

Constraints

• n ≥ 0

• Start with balance = 10

Concept Explanation

Start with balance = 10
After index 0 → 10 - 3 = 7
After index 1 → 7 - 4 = 3
After index 2 → 3 - 5 = -2 → negative

So first negative occurs at index 2.

Step-by-Step Logic

1.Read startingBalance, n, and transactions array.

2.Set balance = startingBalance.

3.Loop from i = 0 to n-1:

• Update balance += transactions[i].

• If balance < 0, return i.

4.If loop finishes and balance never negative, return -1.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
static int firstNegativeBalance(long bal,int[] tx){for(int i=0;i<tx.length;i++){bal+=tx[i];if(bal<0) return i;}return -1;}

Output Example

Input:
10 5 -3 -4 -5 2 1
Output:
2

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