CodingTEST
[SW Expert D2] 1859 : 백만 장자 프로젝트
경걍
2023. 11. 13. 14:11
반응형
1859. 백만 장자 프로젝트
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
문제 풀이
- N일 동안 매매가를 알아내 낼 수 있는 최대 이득을 출력해라
- 하루에 하나만 살 수 있다.
- 팔 때는 여러 개 가능하다.
해결 포인트
- 뒤에서부터 확인한다.
- max 값을 뒤에서부터 알아낸다.
- 현재 값이 max 값보다 작을 경우, [max - 현재값] 만큼에 이득을 본다.
- 현재 값이 max 값보다 클 경우, max를 현재 값으로 변경한다.
코드
import java.util.Scanner;
class Solution
{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++)
{
int N = sc.nextInt();
int [] nums = new int[N];
for(int n=0;n<N;n++) {
nums[n] = sc.nextInt();
}
long max = nums[N-1];
long result = 0;
for(int i=N-2;i>=0;i--) {
if(max > nums[i]) {
result += max - nums[i];
}
else {
max = nums[i];
}
}
System.out.println("#" + test_case + " " + result);
}
}
}
반응형