JAVA Program for Houses Problem (TCS Codevita) | PrepInsta

JAVA Program for Houses Problem

Houses Problem

Tata Consultancy Service puts together a coding competition each year with around more than 200k participants from all over the globe. This competition aims at promoting Programming-As-A-Sport feeling. The solution uses 1D array and some function from the MATH Class , here we have provided a solution in JAVA language for this problem.

Problem Description

Question:- There are n houses build in a line, each of which contains some value in it.

 A thief is going to steal the maximal value of these houses, but he can’t steal in two adjacent houses because the owner of the stolen houses will tell his two neighbours left and right side.

What is the maximum stolen value?

Sample Input: val[] = {6, 7, 1, 3, 8, 2, 5}

Sample Output: 20

JAVA Code

import java.util.Scanner;
public class Main {

    static int prep(int hval[],int n) {
        if(n==0)
            return 0;
        if(n==1)
            return hval[0];
        if(n==2)
            return Math.max(hval[0],hval[1]);

        int[] dp = new int[n];
        dp[0]=hval[0];
        dp[1]=Math.max(hval[0],hval[1]);

        for (int i = 2; i < n; i++) {
            dp[i]=Math.max(hval[i]+dp[i-2],dp[i-1]);
        }
        return dp[n-1];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 

        int hval[] = {3,2,4,6,7,1};
        int n=hval.length;
        System.out.println("Max loot value :"+prep(hval,n));
    }

}
Output
6 7 1 3 8 2 5
20

Houses Problem in other Languages

Python

To find the solution of To find the solution of Houses problem in Python Programming language click on the button below:

Python

C

Sorry, we don’t the solution in C You can provide the solution for this problem in C, below in the comments sections.

C++

To find the solution of Houses problem in C++ Programming language click on the button below:

 C++