病人康复(C++ 滑动窗口)

Challenge 3 description

A patient needs rehabilitation within the next N days (numbered from 0 to N-1). The rehabilitation consists of X sessions. For every
rehabilitation session, other than the last one, the next session is
exactly Y days later.
You are given an array A of N integers listing the costs of the individual rehabilitation sessions on the N days: that is rehabilitation on the K-th day costs A[K].
Write a function:

int solution (int Al], int N, int X, int Y):

that, given the array A and the two integers X and Y, returns the
minimum cost of rehabilitation.
It is guaranteed that it is always possible to complete all X
rehabilitation sessions.
Examples:

  1. Given A = [4, 2, 3, 7], X = 2 and Y = 2, your function should return 7,
    which is the sum of the costs on days 0 and 2 (7 = 4 + 3).
  2. Given A = [10, 3, 4, 7], X = 2 and Y = 3, your function should return 17 since rehabilitation is possible only on days 0 and 3 (17 = 10 + 7).
  3. Given A = [4, 2, 5, 4, 3, 5, 1, 4, 2, 7], X = 3 and Y = 2, your function should return 6, which is the sum of the costs on days 4, 6 and 8 (6 = 3 + 1 + 2).

Write an efficient algorithm for the following assumptions:

  • N and X are integers within the range [2…200,000];
  • each element of array A is an integer within the range [1…1,0001]
  • Y is an integer within the range [1…199,999];
  • N is higher than (X - 1) * Y.

分析

滑动窗口,不这样的话会多很多重复计算,会超时。

#include <iostream>

using namespace std;

/// 核 心 代 码 // 
int solution(int A[], int N, int X, int Y) {
    int res = 0x7FFFFFFF;
    for (int i = 0; i < Y; i++) {
        int count = 0;
        int sum = 0;
        int start = i;
        int end = i;
        while (end < N) {
            sum += A[end]; // 这里是[end]! 粗心写成 i 了,结果老是错, 我是shabby
            count++;
            if (count == X) {
                res = res<sum?res:sum;
                sum -= A[start];
                start += Y;
                count--;
            }
            end += Y;
        }
    }
    return res;
}
/// 核 心 代 码 //

int main () {
    int A[] = {4, 2, 5, 4, 3, 5, 1, 4, 2, 7};
    int B[] = {4, 2, 3, 7};
    cout << solution(A, 10, 3, 2) << endl;
    cout << solution(B, 4, 2, 2);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值