📌  相关文章
📜  查找房屋的最大可能偷窃价值

📅  最后修改于: 2021-04-29 03:12:03             🧑  作者: 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


    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


  • 输出:
    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

    
    
  • 输出:
    Maximum loot value : 19
    
  • 复杂度分析:
    • 时间复杂度: O(n) ,只需要遍历原始数组。因此,时间复杂度为O(n)。
    • 辅助空间: O(1) ,不需要额外的空间,因此空间复杂度是恒定的。