第一题
题目:n×m的方阵,找到一个子方针,方针的大小为l×l且l≥2,方针的价值为其四个角上数字之和,求最大子方针价值。
class Slution1 {
public:
long Ans(vector<vector<long>> a) {
long ret = 0;
int n = a.size(), m = a[0].size();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < m - 1; ++j) {
int k = 1;
// 检测边界
while ((k + i < n) && (k + j) < m) {
long temp = a[i][j] + a[i + k][j] + a[i][j + k] + a[i + k][j + k];
ret = max(ret, temp);
k++;
}
}
}
return ret;
}
};
第二题
题目:给定x,y,a,b四个数,用a乘x或y,找到让a等于b的最小次数,无结果输出-1。
class Slution2 {
private:
int ans = INT_MAX;
bool flag = false;
public:
void fun(int x, int y, long a, long b, int num) {
if (flag) return;
if (a > b) return;
if (a == b) {
flag = true;
ans = num;
return;
}
// 先乘大数再乘小数
fun(x, y, a * x, b, num + 1);
fun(x, y, a * y, b, num + 1);
}
int Ans(long a, long b, int x, int y) {
if (x >= y) {
fun(x, y, a, b, 0);
}
else {
fun(y, x, a, b, 0);
}
if (ans == INT_MAX) {
return -1;
}
else return ans;
}
};
第三题
题目:n个城市,每个城市包含距离x,快乐值y。小明想去任意个城市,找出一些城市,满足其中任意两个城市之间距离小于k,快乐值的和最大,输出快乐值和。
class Slution3 {
public:
int Ans(vector<vector<int>>& c, int k) {
int n = c.size();
sort(c.begin(), c.end(), [](vector<int>& a, vector<int>& b)->bool {
return a[0] < b[0];
});
int l = 0, r = 0;
long sum = 0, ans = 0;
while (l < n && r < n) {
// 差值大于等于k,该移动左边界缩小范围
if (c[r][0] - c[l][0] >= k) {
sum -= c[l][1];
l++;
continue;
}
sum += c[r][1];
ans = max(ans, sum);
r++;
}
return ans;
}
};