<第3節-ダブルポインタ、スライドウィンドウ>3.最大収益


3.最大売上高
<説明>
賢洙のお父さんはお菓子屋を経営しています.賢秀のお父さんは賢秀にN日間の販売記録をあげた.
私は彼にK日間の最大売上高がいくらなのかを手に入れた.
N=10の場合、10日間の販売記録は以下の通りです.K=3なら.
12 15 11 20 25 10 20 19 13 15
3日連続の最大売上高は11+20+25=56万元.
賢秀を助けてくれ
<入力>
1行目はN(5<=N<=10000)とK(2<=K<=N)である.
2行目にはN個の数字列があります.各数値は500未満の負ではなく整数です.
<出力>
最初の行に最大収益を出力します.
===================================================
<コード>
まず、指定日の売上高をMAX値に格納します.そして翌日の売上を保存し、最長日の売上から減算した値をMAXの値と比較し、より大きな値をMAXに保存することで最大の売上を得ることができます.
import java.util.*;

class Main {	
	public int solution(int num,int d,int[] array) {
		int answer=0;
		int max=0;
		int p1=0,p2=0;
		while(p1<d) {
			max+=array[p1++];
		}
		answer=Math.max(answer, max);
		while(d<array.length) {
			max=max+array[d++]-array[p2++];
			answer=Math.max(answer, max);
		}
		return answer;
		
	}
		
		
	public static void main(String[] args) {
		Main main = new Main();
		Scanner scan = new Scanner(System.in);
	   
		int num=scan.nextInt();
		
		int d=scan.nextInt();
		
	    int[] array=new int[num];
		for(int i=0;i<num;i++) {
			array[i]=scan.nextInt();
			}
	 
		System.out.print(main.solution(num,d,array));
		}
}
<重要>
1)日付サイズのフレームを設定し、移動していると考えると、より効率的です.