我们得到一个(6 * 6)2D阵列,我们必须在其中找到最大的沙漏总和。 例如,如果我们在一个充满零的数组中使用数字1创建一个沙漏,它可能如下所示:
沙漏的总和是其中所有数字的总和。上述沙漏的总和分别为7,4和2。
我为它编写了一个代码,如下所示。它基本上是一个竞争性的编程问题,因为我是该领域的新手,我编写了一个非常糟糕的复杂性代码......可能是程序无法生成在规定的时间内所需的输出。下面是我的代码:
int main(){
vector< vector<int> > arr(6,vector<int>(6));
for(int arr_i = 0;arr_i < 6;arr_i++)
{
for(int arr_j = 0;arr_j < 6;arr_j++)
{
cin >> arr[arr_i][arr_j];
}
} //numbers input
int temp; //temporary sum storing variable
int sum=INT_MIN; //largest sum storing variable
for(int i=0;i+2<6;i++) //check if at least3 exist at bottom
{
int c=0; //starting point of traversing column wise for row
while(c+2<6) //three columns exist ahead from index
{
int f=0; //test case variable
while(f!=1)
{ //if array does not meet requirements,no need of more execution
for(int j=c;j<=j+2;j++)
{ //1st and 3rd row middle element is 0 and 2nd row is non 0.
//condition for hourglass stucture
if((j-c)%2==0 && arr[i+1][j]==0||((j-c)%2==1 && arr[i+1][j]!=0)
//storing 3 dimensional subarray sum column wise
temp+=arr[i][j]+arr[i+1][j]+arr[i+2][j]; //sum storage
else
f=1; //end traversing further on failure
if(sum<temp)
sum=temp;
f=1;//exit condition
}//whiel loop of test variable
temp=0; //reset for next subarray execution
c++; /*begin traversal from one index greater column wise till
condition*/
}// while loop of c
}
}
cout<<sum;
return 0;
}
这是我在时间间隔内未能处理的代码的实现。请考虑时间复杂度建议一个更好的解决方案,并随意指出我方在理解问题时的任何错误。问题来自Hackerrank。 如果你需要它,这里是链接: https://www.hackerrank.com/challenges/2d-array
答案 0 :(得分:5)
您的问题的解决方案是:
#include <cstdio>
#include <iostream>
#include <climits>
int main() {
int m[6][6];
// Read 2D Matrix-Array
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
std:: cin >> m[i][j];
}
}
// Compute the sum of hourglasses
long temp_sum = 0, MaxSum = LONG_MIN;
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
if (j + 2 < 6 && i + 2 < 6) {
temp_sum = m[i][j] + m[i][j + 1] + m[i][j + 2] + m[i + 1][j + 1] + m[i + 2][j] + m[i + 2][j + 1] + m[i + 2][j + 2];
if (temp_sum >= MaxSum) {
MaxSum = temp_sum;
}
}
}
}
fprintf(stderr, "Max Sum: %ld\n", MaxSum);
return 0;
}
算法很简单,它总结了左上角的所有沙漏和最后2列,并且没有处理2行,因为它不能形成沙漏。
答案 1 :(得分:2)
上面的代码几乎是正确的,但它对负数组元素不起作用。我们不应该将max sum作为0,因为负数数组可能达不到它们的最大总和&gt; = 0.在这种情况下,初始化INT_MIN的最大总和是更好的选择。
答案 2 :(得分:2)
我在Python 3.0中解决了问题,并通过了HackerRank中的所有测试用例: 想法:只需3个简单步骤:
我已将max初始化为-1000的负值,您也可以使用Minimum_Integer值对其进行初始化
# Complete the hourglassSum function below.
def hourglassSum(arr):
max = -1000
s= []
sub_array = []
for m in range(4)://Move vertically down the rows like(012,123,234,345 and taking 3 values horizontally)
for col in range(4):
for row in range(3):
sub_array.append(arr[row+m][col:col+3])
s = sub_array//Extracting all 16 3X3 matrices
hour_sum = sum_list(s[0])+s[1][1]+sum_list(s[2])//Mask array for hour_glass index[[1,1,1],[0,1,1],[1,1,1]]
if (max<hour_sum):
max = hour_sum
sub_array = []
return max
def sum_list(list1):
total = 0
for ele in range(0, len(list1)):
total = total + list1[ele]
return total
“”“ 其他:尝试在Spyder中替换此代码,以减少代码行 代替
现有:无numpy
hour_sum = sum_list(s[0])+s[1][1]+sum_list(s[2])//Mask array for hour_glass index[[1,1,1],[0,1,1],[1,1,1]]
if (max<hour_sum):
max = hour_sum
使用numpy:
import numpy as np
import numpy.ma as ma
hour_glass = ma.array(sub_array, mask=mask)
sum = hour_glass.data.sum()
“”“
答案 3 :(得分:1)
Swift 4版本:
objectbox-android-objectbrowser
答案 4 :(得分:1)
使用@ Sarthak的否定概念,在@Chema989上使用@Sarthak的回答实现
#!/bin/ruby
arr = Array.new(6)
total = 0
## initilizing as negative integer | in order to work on negative array values
max_total = -1073741824
for arr_i in (0..6-1)
arr_t = gets.strip
arr[arr_i] = arr_t.split(' ').map(&:to_i)
end
## iterating
for i in 0..5
for j in 0..5
if (j+2 < 6) && (i+2 < 6)
total = arr[i][j].to_i + arr[i][j+1].to_i + arr[i][j+2].to_i + arr[i+1][j+1].to_i + arr[i+2][j].to_i + arr[i+2][j+1].to_i + arr[i+2][j+2].to_i
end
## storing max value
if max_total < total
max_total = total
end
end
end
#printing output
puts max_total
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
19
我在HackerRank Challenge中遇到过这个问题:https://www.hackerrank.com/challenges/30-2d-arrays
答案 5 :(得分:1)
这是 JAVA 中有关黑客等级测试的完整代码:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int[][] arr = new int[6][6];
for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}
int max_sum = 0;
int temp_sum;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
temp_sum = 0;
// top row
temp_sum += arr[i][j];
temp_sum += arr[i][j+1];
temp_sum += arr[i][j+2];
//middle
temp_sum += arr[i+1][j+1];
//bottom row
temp_sum += arr[i+2][j];
temp_sum += arr[i+2][j+1];
temp_sum += arr[i+2][j+2];
//if first hourglass, set as max
if(temp_sum > max_sum || i == 0 && j == 0)
max_sum = temp_sum;
}
}
System.out.println(max_sum);
scanner.close();
}
}
答案 6 :(得分:0)
避免四次循环迭代
int main()
{
int arr[6][6],max=-1,sum;
for(int arr_i = 0; arr_i < 6; arr_i++){
for(int arr_j = 0; arr_j < 6; arr_j++){
scanf("%d",&arr[arr_i][arr_j]);
if(arr[arr_i][arr_j]<-9||arr[arr_i][arr_j]>9)
exit(0);
}
}
for(int arr_i = 0; arr_i <4; arr_i++)
{
sum=0;
for(int arr_j = 0; arr_j < 4; arr_j++){
sum=arr[arr_i][arr_j]+arr[arr_i][arr_j+1]+arr[arr_i][arr_j+2]+arr[arr_i+1][arr_j+1]+arr[arr_i+2][arr_j]+arr[arr_i+2][arr_j+1]+arr[arr_i+2][arr_j+2];
if(sum>max)
max=sum;
}
}
printf("%d",max);
return 0;
}
答案 7 :(得分:0)
这是该算法的python实现。
arr = []
for _ in xrange(6):
arr.append(map(int, raw_input().rstrip().split()))
maxSum = -99999999
for row in range(len(arr)):
tempSum = 0
for col in range(len(arr[row])):
if col+2 >= len(arr[row]) or row+2 >= len(arr[col]):
continue
tempSum = arr[row][col] + arr[row][col+1] + arr[row][col+2] + arr[row+1][col+1] + arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
if maxSum < tempSum:
maxSum = tempSum
print(maxSum)
答案 8 :(得分:0)
def hourglassSum(arr)
maxHourGlass = -82
counter = 0
for i in 1..4
for j in 1..4
acc = arr[i][j]
counter= counter +1
for x in -1..1
acc = acc + arr[i-1][j+x] + arr[i+1][j+x]
end
maxHourGlass = acc if acc > maxHourGlass
end
end
maxHourGlass
end
答案 9 :(得分:0)
这是用C ++ 14编写的,并且通过了所有九个测试用例。我认为有人可以改进它以使用更多的C ++ 14功能。
class AppTheme {
setAppBar(context, String title) {
return new AppBa(
floating: true,
pinned: true,
title: Text(title,
style: TextStyle(color: Colors.white),
textDirection: TextDirection.ltr),
flexibleSpace: Container(
decoration: new BoxDecoration(
gradient: new LinearGradient(
colors: [
hexToColor(themeColor1),
hexToColor(themeColor2),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
),
);
}
}
答案 10 :(得分:0)
class Solution {
static void Main(string[] args) {
int[][] arr = new int[6][];
for (int i = 0; i < 6; i++) {
arr[i] = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
}
int[] sum=new int[16];
int j;
int count=0;
for(int i=0; i<4; i++)
{
for(j=0;j<4;j++)
{
if(count<16)
{
sum[count]=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
count++;
}
}
}
int max=sum.Max();
Console.WriteLine(max);
}
}
答案 11 :(得分:0)
Java解决方案通过了所有8个HackerRank测试用例,并且是解决方案的模块化一部分。我重构了计算单个沙漏的逻辑:
static int hourglassSum(int[][] arr) {
if (arr.length < 3){
return 0;
}
int tempSum = 0;
int max = Integer.MIN_VALUE;
for (int i=0; i < 6; ++i){
for (int j=0; j < 6; ++j){
if (j+2<6 && i+2<6){
tempSum = oneHourGlassSum(arr, i, j);
if (tempSum > max) {
max = tempSum;
}
}
}
}
return max;
}
static int oneHourGlassSum(int [][] arr, int sRow, int sCol){
int tempSum = arr[sRow][sCol] + arr[sRow][sCol+1] + arr[sRow][sCol+2];
tempSum += arr[sRow+1][sCol+1];
tempSum += arr[sRow+2][sCol+0] + arr[sRow+2][sCol+1] + arr[sRow+2][sCol+2];
return tempSum;
}
答案 12 :(得分:0)
在数组中找到的最大(最大)沙漏总数将为-63,因为元素不能大于-9,即-9 * 7 = -63
C#
int max_hourglass_sum = -63;
for (int i = 0; i <arr.Length-2; i++) { //row
for (int j = 0 ; j<arr.Length-2; j++) { //column
int current_hourglass_sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] //1st row
+ arr[i+1][j+1] //2nd row
+ arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] ;//3rd row
max_hourglass_sum = Math.Max(max_hourglass_sum , current_hourglass_sum);
}
}
答案 13 :(得分:0)
JAVA 这是我做过的非常简单的Java实现。尝试将max设置为-63而不是-10000以获得更快的结果
int max=-63;
int sum=0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]
+ arr[i+1][j+1]
+ arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
if(sum>max){
max=sum;
}
}
}System.out.println(max);
答案 14 :(得分:0)
这是一个常见的问题,在许多不同的解决问题中都会被问到。
这是JavaScript的解决方案,以防万一有人需要。
function hourglassSum(arr) {
let highestSum = null;
for (let i = 0; i <= 3; i++) {
for (let j = 0; j <= 3; j++) {
let sum = (
arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +
arr[i + 1][j + 1] +
arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]
);
if (highestSum === null || sum > highestSum) {
highestSum = sum;
}
}
}
return highestSum;
}
// Sample Input
const matrix = [
[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 0, 2, 4, 4, 0],
[0, 0, 0, 2, 0, 0],
[0, 0, 1, 2, 4, 0]
];
console.log(hourglassSum(matrix)); // Output = 19
答案 15 :(得分:0)
java基本解决方案;
static int hourglassSum(int[][] arr) {
int sum = 0;
for(int i = 2; i<6; i++){
for(int j = 2; j<6; j++){
int up = arr[i-2][j-2] + arr[i-2][j-1] + arr[i-2][j];
int mid = arr[i-1][j-1];
int down = arr[i][j-2] + arr[i][j-1] + arr[i][j];
if(up+mid+down > sum){
sum = up+mid+down;
}
}
}
return sum;
}
答案 16 :(得分:0)
static int hourglassSum(int[][] arr) {
int result = int.MinValue;
int rowLength = arr.GetLength(0);
int colLength = arr.Length;
for (int i = 0; i < rowLength - 2; i++)
{
for(int j=0; j< colLength - 2; j++)
{
int sum = 0;
sum = arr[i][j] + arr[i][j+1] + arr[i][j+2]+ arr[i+1][j+1]
+ arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
result = Math.Max(result,sum);
}
}
return result;
}