From d1f31a5766a14738e20850cb941433e96622f631 Mon Sep 17 00:00:00 2001 From: Arjun Sharma Date: Fri, 17 Oct 2025 13:27:38 +0530 Subject: [PATCH] Implement solution for guessing game cost calculation --- GuessNumberhigherorlower | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 GuessNumberhigherorlower diff --git a/GuessNumberhigherorlower b/GuessNumberhigherorlower new file mode 100644 index 0000000..72b36b7 --- /dev/null +++ b/GuessNumberhigherorlower @@ -0,0 +1,23 @@ +class Solution { + public int getMoneyAmount(int n) { + int[][] dp = new int[n + 1][n + 1]; + + return calculateCost(1, n, dp); + } + + private int calculateCost(int start, int end, int[][] dp) { + if (start >= end) return 0; + + if (dp[start][end] != 0) return dp[start][end]; + + int minCost = Integer.MAX_VALUE; + + for (int guess = (start + end) / 2; guess <= end; guess++) { + int cost = guess + Math.max(calculateCost(start, guess - 1, dp), calculateCost(guess + 1, end, dp)); + minCost = Math.min(minCost, cost); + } + + dp[start][end] = minCost; + return minCost; + } +}