초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
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;
}
}
https://github.com/shyeon4643/algorithm/blob/main/src/programmers/Solution7.java