코딩테스트/리트코드LeetCode

[리트코드LeetCode][Easy][JAVA]2769. Find the Maximum Achievable Number

빔o0O 2024. 12. 29. 14:06

 

문제

Given two integers, num and t. A number is achievable if it can become equal to num after applying the following operation:

  • Increase or decrease the number by 1, and simultaneously increase or decrease num by 1.

Return the maximum achievable number after applying the operation at most t times.

 

Example 1:

Input: num = 4, t = 1

Output: 6

Explanation:

Apply the following operation once to make the maximum achievable number equal to num:

  • Decrease the maximum achievable number by 1, and increase num by 1.

Example 2:

Input: num = 3, t = 2

Output: 7

Explanation:

Apply the following operation twice to make the maximum achievable number equal to num:

  • Decrease the maximum achievable number by 1, and increase num by 1.

 

Constraints:

  • 1 <= num, t <= 50

 

 


 

분석

  1. 두 개의 정수(integer) num 과 t가 주어진다.
    그리고 어떤 숫자(number)와 num을 각각 동시에 1씩 증가/감소시켰을 때 그 숫자 number가 num과 같아지면 그 숫자는 achievable 숫자이다(number와 num의 증가/감소 연산은 서로 반대로 진행한다).
    최대 t 번 이 연산을 반복하였을 때 가장 큰 achievable 숫자를 구하여 return한다. 
  2. 가장 큰 값을 구해야 하므로 number 에서 1씩 감소시키면서 증가된 num과 같아지는 경우가 필요하고, 그러므로 number는 num 보다 큰 수가 된다.
  3. 감소/증가를 1번 하면 number와 num의 숫자 차이가 2가 감소한 것이다.
  4. number는 1씩 감소, num은 1씩 증가함을 n번(n<=t) 반복하여 어떤 한 지점에서 숫자가 동일해진다고 했을 때, number는 num+(2*n) 인 값이라고 볼 수 있다. 그리고 이 증감은 최대 t번이 가능하고, 최대로 수행해야 가장 큰 값을 구할 수 있기 때문에 결과적으로 도출해야하는 값은 num+(2*t) 이다.

 

 

 


 

피드백

  1. 어떤 알고리즘이 필요하다기 보단 문제 해석이 중요했던 것 같다. 나름대로 잘 풀어낸 것 같아서 만족.

 

 

 


 

답안

class Solution {
    public int theMaximumAchievableX(int num, int t) {
        return num + (2*t);
    }
}

 

 

 


 

다른 사람의 답안

class Solution {
    public int theMaximumAchievableX(int num, int t) {
        for(int i = 0; i < t; i++) {
			num+=2;
		}
		
		return num;
    }
}

 

 

 

 

 

 


 

🔗링크