[프로그래머스] 주식가격(42584)

lhs's avatar
Nov 21, 2024
[프로그래머스] 주식가격(42584)
 

1. 문제 풀이 아이디어

  • 뒤에서부터 결과를 계산하면 문제를 풀 수 있다.

2. 나의 정답 코드

class Solution { public int[] solution(int[] prices) { int[] answer = new int[prices.length]; for (int i = prices.length - 2; i >= 0; i--) { for (int j = i + 1; j < prices.length; j++) { if (j == prices.length - 1 || prices[i] > prices[j]) { answer[i] = j - i; break; } if (prices[i] == prices[j]) { answer[i] = answer[j] + j - i; break; } } } return answer; } }

3. 정리

  • 이중 for문을 사용해 prices.length - 2 인덱스부터 0까지의 값을 계산한다.
  • 만약 j번째 prices 값이 i번째 prices 값보다 작거나 j가 마지막 인덱스일 경우, j - i로 결과값을 구한다.
  • 만약 j번째 prices 값이 i번째 prices 값과 같다면, j번째 결과값에 j - i를 더해 결과값을 구한다.
 
Share article

LHS's Study Space