[Programmers] 주식 가격

밀크야살빼자·2023년 11월 21일
0
post-thumbnail

문제

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.

제한 사항

  • prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
  • prices의 길이는 2 이상 100,000 이하입니다.

입출력 예

기능 명세서

  • 1초 시점에서 보았을 때, 1 아래로 떨어지는 가격이 없다 -> 4초

  • 2초 시점에서는 2 아래로 떨어지는 가격이 없다 -> 3초

  • 3초 시점에서는 3 아래로 떨어지는 가격이 있다. 이때, 가격이 1초 뒤에 떨어지기 때문에 1초

  • 현재 시점에 있는 가격이 같거나 크면 +1초

  • 현재 시점에 있는 가격보다 떨어지면 +1초 후 break

❌첫 번째 실패한 코드❌

import java.util.*;
class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        int time=0;
        for(int i=0; i<prices.length;i++){
            for(int j=i;j<prices.length;j++){
                if(prices[i]<=prices[j]){
                    time++;
                }else{
                    time++; 
                    break;
                } 
            }
            answer[i]=time;
            time=0;
        }
        return answer;
    }
 }

이 코드에서 테스트 결과가 아래 사진 처럼 결과값보다 1씩 크게 나왔다.

그래서 전체 time 값에 -1 해준 후 answer 배열에 저장! 결과는 성공!

✅성공한 코드

import java.util.*;
class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        int time=0;
        for(int i=0; i<prices.length;i++){
            for(int j=i;j<prices.length;j++){
                if(prices[i]<=prices[j]){
                    time++;
                }else{
                    time++; 
                    break;
                } 
            }
            answer[i]=time-1;
            time=0;
        }
        return answer;
    }
 }

Github

https://github.com/shyeon4643/algorithm/blob/main/src/programmers/Solution7.java

profile
기록기록기록기록기록

0개의 댓글