2022.11.16 PM 02:45 by CBJ
來源 : https://zerojudge.tw/ShowProblem?problemid=h081 出題者 : 2022年1月APCS 標籤 : 迴圈、條件判斷 難易度 : 1
解題想法 : 依據題意實作即可(注意:題目的index是從1開始,而程式語言大多從0開始,這點要特別注意!)
//C language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/APCS/h081.c
#include<stdio.h>
int main(){
int have,now,profit=0,n,D,i,j,sell=0,price[101];
scanf("%d%d",&n,&D);
for(i=0;i<n;i++){
scanf("%d",&price[i]);
}
have = price[0];
now = 1;
for(j=1;j<n;j++){
if(now){
if(price[j]>=(have+D)){
profit+=(price[j]-have);
sell = price[j];
now = 0;
}
}else if(price[j]<=(sell-D)){
have = price[j];
now = 1;
}
}
printf("%d\n",profit);
}

//C++ language
//solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/APCS/h081.cpp
#include<iostream>
#include<vector>
using namespace std;
int main(){
int have,now,profit=0,n,D,sell=0;
cin>>n>>D;
vector<int>price(101);
for(int i=0;i<n;i++){
cin>>price[i];
}
have=price.front();
now=1;
for(int i=1;i<n;i++){
if(now){
if(price[i]>=have+D){
profit+=price[i]-have;
sell=price[i];
now=0;
}
}
else if(price[i]<=sell-D){
have=price[i];
now=1;
}
}
cout<<profit<<"\n";
}

## Python language
## solution link(含註解): https://github.com/CBJ0519/CBJsProgramDiary.com/blob/main/APCS/h081.py
sell=profit=0
n,d=map(int,input().split())
price=[int(x) for x in input().split()]
have=price[0]
now=1
for i in price[1:]:
if now:
if i>=(have+d):
profit+=(i-have)
sell=i
now=0
elif i<=(sell-d):
have=i
now=1
print(profit)

發佈留言