Problem Statement
Josh loves playing with blocks. Currently, he has N blocks, labeled 0 through N-1. The heights of all blocks are positive integers. More precisely, for each i, the height of block i is blockHeights[i]. Josh is interested in making the tallest block tower possible. He likes all his towers to follow three simple rules:- The blocks must be stacked in a single column, one atop another. The height of the tower is simply the sum of heights of all its blocks.
- The labels of blocks used in the tower must increase from the bottom to the top. In other words, whenever Josh places box x on top of box y, we have x > y.
- Josh will never place a box of an even height on top of a box of an odd height.
Definition
Class: | BlockTower |
Method: | getTallest |
Parameters: | int[] |
Returns: | int |
Method signature: | int getTallest(int[] blockHeights) |
(be sure your method is public) |
Constraints
-blockHeights will contain between 1 and 50 elements, inclusive.-Each element of blockHeights will be between 1 and 50, inclusive.Examples
0)
| ||
Returns: 11 | ||
|
| ||
Returns: 7 | ||
|
| ||
Returns: 7 | ||
| ||
Returns: 4 | ||
| ||
Returns: 196 | ||
|
| ||
Returns: 147 | ||
| |
Returns: 273 | |
#include<vector>
#include<cstdio>
#include<cstdlib>
using namespace std;
class BlockTower
{
public:
int getTallest(vector<int> blockHeights)
{
int total = 0;
int n = blockHeights.size();
for(int limit = 0; limit <= n; limit++)
{
int ans = 0;
for(int i=0;i<limit;i++)
if(blockHeights[i]%2==0)
ans += blockHeights[i];
for(int i=limit; i<n;i++)
if(blockHeights[i]%2)
ans += blockHeights[i];
total = max(total,ans);
}
return total;
}
};
Cách 2:
#include<vector>
#include<cstdio>
#include<cstdlib>
using namespace std;
class BlockTower
{
public:
int getTallest(vector<int> blockHeights)
{
int total = 0;
vector<int> old;
vector<int> eve;
int n = blockHeights.size();
old.resize(n,0);
eve.resize(n,0);
if(blockHeights[0]%2)
{
old[0] = blockHeights[0];
}
else
{
eve[0] = blockHeights[0];
}
for(int i=1;i<n;i++)
{
if(blockHeights[i]%2)
{
old[i] += old[i-1] + blockHeights[i];
eve[i] = eve[i-1];
}
else
{
eve[i] = eve[i-1] + blockHeights[i];
old[i] = old[i-1];
}
}
if(blockHeights[0]%2==0)
total = eve[0] + old[n-1];
else
total = old[n-1];
for(int i=1;i<n;i++)
total = max(total,eve[i] + old[n-1] - old[i-1]);
return total;
}
};
Không có nhận xét nào:
Đăng nhận xét