Balance tracker

Balance tracker

Medium Java Variables 22 views
Explanation Complexity

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

Example

10
5
-3 -4 -5 2 1
2

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 Explanation

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.

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 Explanation

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.

Input / Output Format

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

Examples

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

Example Solution (Public)

Java
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;}

Official Solution Code

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;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.