奇安信C/C++:笔试记录,两题AC
1. 简单滑动窗口
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * M包糖果,抛M次硬币,硬币连续n次为正面,最多能得到多少颗糖果 * @param candies int整型vector 每包糖果的数量 * @param coin int整型vector 抛硬币的结果 * @param n int整型 连续是正面的次数 * @return int整型 */ int maxCandies(vector<int>& candies, vector<int>& coin, int n) { // write code here int cur = 0; int cn = candies.size(); for (int i= 0; i< coin.size(); i++) { if (coin[i] == 0) cur += candies[i]; } //cout << cur << endl; int res = 0; int left = 0, right = n-1; while (right< cn) { int temp = cur; for (int i= left; i<= right; i++) { if (coin[i] != 0) { temp += candies[i]; } } //cout << temp << endl; res = max(res, temp); ++left; ++right; } return res; } };
class Solution { public: /** * 获得剩余区域内的最大干净矩形面积 * @param x1 int整型 * @param y1 int整型 * @param x2 int整型 * @param y2 int整型 * @param x3 int整型 * @param y3 int整型 * @param x4 int整型 * @param y4 int整型 * @return int整型 */ int maxRectangle(vector<vector<int>>& m) { int r= m.size(); int c = m[0].size(); vector<vector<int> > dp(r, vector<int>(c, 0)); int max_area = 0; for (int i= 0; i< r; i++) { for (int j= 0; j< c; j++) { if (m[i][j] == 1) { dp[i][j] = j==0? 1 : dp[i][j-1]+1; int width = dp[i][j]; for (int k= i; k>= 0; k--) { width = min(width, dp[k][j]); max_area = max(max_area, width * (i-k+1)); } } } } return max_area; } int getMaxArea(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { // write code here vector<vector<int> > m(10, vector<int>(10, 1)); if (x2<x1) swap(x1,x2); if (y2<y1) swap(y1,y2); if (x4<x3) swap(x3,x4); if (y4<y3) swap(y3,y4); for (int y= y1; y< y2; y++) { for (int x= x1; x< x2; x++) { m[y][x] = 0; } } for (int y= y3; y< y4; y++) { for (int x= x3; x< x4; x++) { m[y][x] = 0; } } return maxRectangle(m); } };