🦕 공룡이 되자!

[프로그래머스] Java 주식가격 본문

Development/CodingTest

[프로그래머스] Java 주식가격

Kirok Kim 2021. 12. 13. 21:42
class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        
      for (int i = 0; i < prices.length; i++) {
				int cnt = 0;
				for (int j = i + 1; j < prices.length; j++) {
					if (i == prices.length - 1) {
						cnt = 0;
						break;
					} else if (prices[i] <= prices[j]) {
						cnt++;
					} else if (prices[i] > prices[j]) {
						cnt++;
						break;
					}
				}
			answer[i] = cnt;
	    }
             return answer;
		}
}
  • 리턴되는 횟수를 cnt라고 지정을하고 1초 뒤의 가격과 비교하여 cnt를 측정했다.
  • 조금 더 간단히 하려면 cnt를 없애고 answer의 배열에 ++시키면 조금 더 줄일 수 있다.
  • 아래는 프로그래머스 문제 풀이다.
class Solution {
    public int[] solution(int[] prices) {
        int len = prices.length;
        int[] answer = new int[len];
        int i, j;
        for (i = 0; i < len; i++) {
            for (j = i + 1; j < len; j++) {
                answer[i]++;
                if (prices[i] > prices[j])
                    break;
            }
        }
        return answer;
    }
}

 

반응형
Comments