今日頭條2018 AI Camp筆試編程題——最小分割分數

在這裏插入圖片描述
代碼:

#include <iostream>
using namespace std;
int max_ = 0;
int sum = 0;
int sum_temp = 0;
int count_ = 0;
//n is the length of arr,m is the number of your split.
int func(int* arr,int n,int m)
{
    for(int i=0;i<n;++i)//this loop is to get the max and sum,is also the floor and ceil of next loop.
    {
        if(arr[i]>max_)
        {
            max_ = arr[i];
        }
        sum+=arr[i];
    }
    for(int j=max_;j<=sum;j++)//between the max and sum,we make a loop to get the smallest number that meets the condition.
    {
        for(int k=0;k<n;k++)
        {
            sum_temp += arr[k];
            if (sum_temp > j)//when the current sum of this part is bigger than j,we split.
            {
                count_++;
                sum_temp = arr[k];
            }
        }
        if(count_ < m)//when count_ < m,we say this j meets the condition.Because since you can split it by count_ times,
            // and count_<=m-1,so you must be able to split it by m-1 times,and of course get m parts, the sum of each part <=j.
        {
            return j;
        }

        else
        {
            count_ = 0;// if there is no count_<m,we set the count_ 0.and j+=1,begin next loop,until we get the smallest j
            //that meets the condition.
            sum_temp = 0;
        }
    }
    return sum;//if all cases can't meet the condition,so the sum of arr will be returned.
}
int main(){
    int array_test[5] = {1,4,2,3,5};
    cout<<func(array_test,5,3);
    return 0;
}

參考:
https://blog.csdn.net/seniusen/article/details/80539553

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章