📌  相关文章
📜  从房屋中找出最大可能的被盗价值

📅  最后修改于: 2021-09-17 07:22:53             🧑  作者: Mango

在一条线上建造了 n 栋房屋,每栋房屋都包含一些价值。一个小偷要偷走这些房子的最大价值,但他不能偷走相邻的两个房子,因为被盗房子的主人会告诉他左右两个邻居。最大被盗价值是多少?
例子:

Input: hval[] = {6, 7, 1, 3, 8, 2, 4}
Output: 19

Explanation: The thief will steal 6, 1, 8 and 4 from the house.

Input: hval[] = {5, 3, 4, 11, 2}
Output: 16

Explanation: Thief will steal 5 and 11

朴素的方法给定一个数组,解决方案是找到没有两个选定元素相邻的最大和子序列。因此,解决问题的方法是递归解决方案。所以有两种情况。

  1. 如果选择了一个元素,则无法选择下一个元素。
  2. 如果没有选择一个元素,则可以选择下一个元素。

因此,可以轻松设计递归解决方案。可以存储子问题,从而降低复杂性并将递归解决方案转换为动态规划问题。

算法:

  1. 创建一个额外的空间dp , DP 数组来存储子问题。
  2. 处理一些基本情况,如果数组长度为0,则打印0,如果数组长度为1,则打印第一个元素,如果数组长度为2,则打印最多两个元素。
  3. dp[0]更新为array[0] ,将dp[1] 更新array[0]array[1] 的最大值
  4. 从第二个元素(第二个索引)到数组末尾遍历数组。
  5. 对于每个索引,将dp[i]更新为dp[i-2] + array[i]dp[i-1] 的最大值,这一步定义了两种情况,如果选择了一个元素,则不能选择前一个元素如果未选择元素,则可以选择前一个元素。
  6. 打印值dp[n-1]

执行:

C++
// CPP program to find the maximum stolen value
#include 
using namespace std;
 
// calculate the maximum stolen value
int maxLoot(int *hval, int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return hval[0];
    if (n == 2)
        return max(hval[0], hval[1]);
 
    // dp[i] represent the maximum value stolen
    // so far after reaching house i.
    int dp[n];
 
    // Initialize the dp[0] and dp[1]
    dp[0] = hval[0];
    dp[1] = max(hval[0], hval[1]);
 
    // Fill remaining positions
    for (int i = 2; i


Java
// Java program to find the maximum stolen value
import java.io.*;
 
class GFG
{
    // Function to calculate the maximum stolen value
    static int maxLoot(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]);
  
        // dp[i] represent the maximum value stolen
        // so far after reaching house i.
        int[] dp = new int[n];
  
        // Initialize the dp[0] and dp[1]
        dp[0] = hval[0];
        dp[1] = Math.max(hval[0], hval[1]);
  
        // Fill remaining positions
        for (int i = 2; i


Python
# Python3 program to find the maximum stolen value
 
# calculate the maximum stolen value
def maximize_loot(hval, n):
    if n == 0:
        return 0
    if n == 1:
        return hval[0]
    if n == 2:
        return max(hval[0], hval[1])
 
    # dp[i] represent the maximum value stolen so
    # for after reaching house i.
    dp = [0]*n
 
    # Initialize the dp[0] and dp[1]
    dp[0] = hval[0]
    dp[1] = max(hval[0], hval[1])
     
    # Fill remaining positions
    for i in range(2, n):
        dp[i] = max(hval[i]+dp[i-2], dp[i-1])
 
    return dp[-1]
 
# Driver to test above code
def main():
 
    # Value of houses
    hval = [6, 7, 1, 3, 8, 2, 4]
 
    # number of houses
    n = len(hval)
    print("Maximum loot value : {}".
        format(maximize_loot(hval, n)))
 
if __name__ == '__main__':
    main()


C#
// C# program to find the
// maximum stolen value
using System;
         
class GFG
{
   // Function to calculate the
   // maximum stolen value
    static int maxLoot(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]);
 
        // dp[i] represent the maximum value stolen
        // so far after reaching house i.
        int[] dp = new int[n];
 
        // Initialize the dp[0] and dp[1]
        dp[0] = hval[0];
        dp[1] = Math.Max(hval[0], hval[1]);
 
        // Fill remaining positions
        for (int i = 2; i


PHP


Javascript


C++
// C++ program to find the maximum stolen value
#include 
using namespace std;
 
// calculate the maximum stolen value
int maxLoot(int *hval, int n)
{
    if (n == 0)
        return 0;
 
    int value1 = hval[0];
    if (n == 1)
        return value1;
 
    int value2 = max(hval[0], hval[1]);
    if (n == 2)
        return value2;
 
    // contains maximum stolen value at the end
    int max_val;
 
    // Fill remaining positions
    for (int i=2; i


Java
// Java program to find the maximum stolen value
import java.io.*;
 
class GFG
{
    // Function to calculate the maximum stolen value
    static int maxLoot(int hval[], int n)
    {
        if (n == 0)
        return 0;
  
        int value1 = hval[0];
        if (n == 1)
            return value1;
  
        int value2 = Math.max(hval[0], hval[1]);
        if (n == 2)
            return value2;
   
        // contains maximum stolen value at the end
        int max_val = 0;
  
        // Fill remaining positions
        for (int i=2; i


Python
# Python3 program to find the maximum stolen value
 
# calculate the maximum stolen value
def maximize_loot(hval, n):
    if n == 0:
        return 0
 
    value1 = hval[0]
    if n == 1:
        return value1
 
    value2 = max(hval[0], hval[1])
    if n == 2:
        return value2
 
    # contains maximum stolen value at the end
    max_val = None
 
    # Fill remaining positions
    for i in range(2, n):
        max_val = max(hval[i]+value1, value2)
        value1 = value2
        value2 = max_val
 
    return max_val
 
# Driver to test above code
def main():
 
    # Value of houses
    hval = [6, 7, 1, 3, 8, 2, 4]
 
    # number of houses
    n = len(hval)
    print("Maximum loot value : {}".format(maximize_loot(hval, n)))
 
if __name__ == '__main__':
    main()


C#
// C# program to find the
// maximum stolen value
using System;
         
public class GFG
{
    // Function to calculate the
    // maximum stolen value
    static int maxLoot(int []hval, int n)
    {
        if (n == 0)
        return 0;
 
        int value1 = hval[0];
        if (n == 1)
            return value1;
 
        int value2 = Math.Max(hval[0], hval[1]);
        if (n == 2)
            return value2;
     
        // contains maximum stolen value at the end
        int max_val = 0;
 
        // Fill remaining positions
        for (int i = 2; i < n; i++)
        {
            max_val = Math.Max(hval[i] + value1, value2);
            value1 = value2;
            value2 = max_val;
        }
 
        return max_val;
    }
     
    // Driver program
    public static void Main ()
    {
        int []hval = {6, 7, 1, 3, 8, 2, 4};
        int n = hval.Length;
        Console.WriteLine("Maximum loot value : " +
                                 maxLoot(hval, n));
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


输出:

Maximum loot value : 19

复杂度分析:

  • 时间复杂度: O(n)     .
    只需要对原始数组进行一次遍历。所以时间复杂度是 O(n)
  • 空间复杂度: O(n)     .
    需要一个大小为 n 的数组,因此空间复杂度为 O(n)。

有效的方法:通过仔细观察DP数组,可以看出在计算索引值时前两个索引的值很重要。用两个变量替换总 DP 数组。

算法:

  1. 处理一些基本情况,如果数组长度为0,则打印0,如果数组长度为1,则打印第一个元素,如果数组长度为2,则打印最多两个元素。
  2. 创建两个变量value1value2 value1作为array[0]value2作为array[0]array[1] 的最大值以及一个变量max_val来存储答案
  3. 从第二个元素(第二个索引)到数组末尾遍历数组。
  4. 对于每个索引,将max_val更新为value1 + array[i]value2 的最大值,这一步定义了两种情况,如果选择了一个元素,则不能选择前一个元素,如果没有选择一个元素,则可以选择前一个元素被选中。
  5. 对于每个索引,更新value1 = value2value2 = max_val
  6. 打印max_val的值

执行:

C++

// C++ program to find the maximum stolen value
#include 
using namespace std;
 
// calculate the maximum stolen value
int maxLoot(int *hval, int n)
{
    if (n == 0)
        return 0;
 
    int value1 = hval[0];
    if (n == 1)
        return value1;
 
    int value2 = max(hval[0], hval[1]);
    if (n == 2)
        return value2;
 
    // contains maximum stolen value at the end
    int max_val;
 
    // Fill remaining positions
    for (int i=2; i

Java

// Java program to find the maximum stolen value
import java.io.*;
 
class GFG
{
    // Function to calculate the maximum stolen value
    static int maxLoot(int hval[], int n)
    {
        if (n == 0)
        return 0;
  
        int value1 = hval[0];
        if (n == 1)
            return value1;
  
        int value2 = Math.max(hval[0], hval[1]);
        if (n == 2)
            return value2;
   
        // contains maximum stolen value at the end
        int max_val = 0;
  
        // Fill remaining positions
        for (int i=2; i

Python

# Python3 program to find the maximum stolen value
 
# calculate the maximum stolen value
def maximize_loot(hval, n):
    if n == 0:
        return 0
 
    value1 = hval[0]
    if n == 1:
        return value1
 
    value2 = max(hval[0], hval[1])
    if n == 2:
        return value2
 
    # contains maximum stolen value at the end
    max_val = None
 
    # Fill remaining positions
    for i in range(2, n):
        max_val = max(hval[i]+value1, value2)
        value1 = value2
        value2 = max_val
 
    return max_val
 
# Driver to test above code
def main():
 
    # Value of houses
    hval = [6, 7, 1, 3, 8, 2, 4]
 
    # number of houses
    n = len(hval)
    print("Maximum loot value : {}".format(maximize_loot(hval, n)))
 
if __name__ == '__main__':
    main()

C#

// C# program to find the
// maximum stolen value
using System;
         
public class GFG
{
    // Function to calculate the
    // maximum stolen value
    static int maxLoot(int []hval, int n)
    {
        if (n == 0)
        return 0;
 
        int value1 = hval[0];
        if (n == 1)
            return value1;
 
        int value2 = Math.Max(hval[0], hval[1]);
        if (n == 2)
            return value2;
     
        // contains maximum stolen value at the end
        int max_val = 0;
 
        // Fill remaining positions
        for (int i = 2; i < n; i++)
        {
            max_val = Math.Max(hval[i] + value1, value2);
            value1 = value2;
            value2 = max_val;
        }
 
        return max_val;
    }
     
    // Driver program
    public static void Main ()
    {
        int []hval = {6, 7, 1, 3, 8, 2, 4};
        int n = hval.Length;
        Console.WriteLine("Maximum loot value : " +
                                 maxLoot(hval, n));
    }
}
 
// This code is contributed by Sam007

PHP


Javascript


输出:

Maximum loot value : 19

复杂度分析:

  • 时间复杂度: O(n)     , 只需要对原始数组进行一次遍历。所以时间复杂度是O(n)。
  • 辅助空间: O(1)     , 不需要额外的空间,所以空间复杂度是恒定的。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程