Problem · Greedy

Maximum Number of Days to Survive

Learn this problem
MediumAmazonOA
See Amazon hiring insights

Problem statement

A lender lent money to a borrower, each day a different lender lent the money to the borrower. The borrower borrowed money on the jth day should payback on the (j+1)th day to maintain good credit and avoid defaulting. The borrower can payback the jth day loan from the (j+1)th day's borrowed money and can use the leftover money on that day. Find the maximum number of days the borrower can survive before defaulting.

lender[i] represents the ith lending amount, and payback[i] represents the ith payback amount.

Function

maximumNumberOfDaysToSurvive(lender: int[], payback: int[]) → int

Complete the function maximumNumberOfDaysToSurvive in the editor.

maximumNumberOfDaysToSurvive has the following parameters:

  1. int[] lender: an array of integers representing the lending amounts
  2. int[] payback: an array of integers representing the payback amounts

Returns

int: the maximum number of days the borrower can survive before defaulting

Examples

Example 1

lender = [4, 6, 1, 8]payback = [7, 10, 3, 9]return = 3

1. Choose lender -> 1, so payback is 3.
2. Choose lender -> 4, repay previous payback 3, hence remaining 4-3 = 1 (borrower spends it), the current Payback is 7.
3. Choose lender -> 8, repay previous payback 7, hence remaining 8-7 = 1 (borrower spends it), the current Payback is 9.
4. Left with lender -> 6, cannot repay previous payback which is 9, 9 > 6 hence default.

So the borrower can survive 3 days.

Example 2

lender = [2, 1, 5]payback = [2, 2, 5]return = 3

The borrower can pay back each day's loan with the next day's borrowed money without any leftover, thus surviving for all 3 days.

Example 3

lender = [1, 1, 1, 2]payback = [2, 2, 2, 3]return = 2

1. Choose lender -> 1, so payback is 2.
2. Choose lender -> 1, repay previous payback 2, hence no remaining (borrower spends it), the current Payback is 2.
3. Left with lender -> 1, cannot repay previous payback which is 2, 2 > 1 hence default.

So the borrower can survive 2 days.

More Amazon problems

drafts saved locally
public int maximumNumberOfDaysToSurvive(int[] lender, int[] payback) {
  // write your code here
}
lender[4, 6, 1, 8]
payback[7, 10, 3, 9]
expected3
checking account