본문 바로가기

백준 문제풀이/Greedy

[C++] 백준 문제풀이 (Greedy) 11501번 주식

 

 

https://www.acmicpc.net/problem/11501

 

11501번: 주식

입력의 첫 줄에는 테스트케이스 수를 나타내는 자연수 T가 주어진다. 각 테스트케이스 별로 첫 줄에는 날의 수를 나타내는 자연수 N(2 ≤ N ≤ 1,000,000)이 주어지고, 둘째 줄에는 날 별 주가를 나타

www.acmicpc.net

 

 

 

#include <bits/stdc++.h>
// [C++] 백준 문제풀이 (Greedy)


int t, n;
int stocks[1000000];


int main(int argc, char *argv[])
{
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(nullptr);

	std::cin >> t;
	while(t--) {
		std::cin >> n;
		long long ret = 0;
		for (int i = 0; i < n; ++i){
			std::cin >> stocks[i];
		}

		for (int i = n - 1; i > 0;){
			int j = i - 1;
			while(j >= 0 && stocks[i] > stocks[j]){
				ret += (stocks[i] - stocks[j]);
				--j;
			}
			i = j;
		}

		std::cout << ret << "\n";
	}
	return 0;
}