Wednesday, November 25, 2015

Airbnb: Maximum Room Days

给一个数组代表reservation request,suppose start date, end date back to back.
比如[5,1,1,5]代表如下预定:
Jul 1-Jul6
Jul6-Jul7
Jul7-Jul8
jul8-Jul13
当然最开始那个Jul 1是随便选就好的啦。
现在input的意义搞清楚了。还有一个限制,就是退房跟开始不能是同一天,比如如果接了Jul 1-Jul6,Jul6-Jul7就不能接了。那问题就是给你个数组,算算最多能把房子租出去多少天。这个例子的话就是10天。. 1point3acres.com/bbs
[4,9,6]=10. visit 1point3acres.com for more.

[4,10,3,1,5]=1

Understand the problem:
This problem is similar to the Leetcode House Robbery
http://buttercola.blogspot.com/2015/08/leetcode-house-robber.html

Code (Java):
import java.io.*;
import java.util.*;

public class Solution {
  public static int getMaxRentalDays(int[] nums) {
    if (nums == null || nums.length == 0) {
      return 0;
    }
    
    int prev2 = 0;
    int prev1 = nums[0];
    
    for (int i = 2; i <= nums.length; i++) {
      int curr = Math.max(prev1, prev2 + nums[i - 1]);
      
      prev2 = prev1;
      prev1 = curr;
    }
    
    return prev1;
  }
  
  public static void main(String[] args) {
    int[] nums = new int[]{4,10,3,1,5};
    
    int result = getMaxRentalDays(nums);
    
    System.out.println(result);
  }
}

No comments:

Post a Comment