阿里5.19笔试
两道算法60min
1.一个多维数组,每次可以对两个公共边位置进行*-1运算,求出该数组的最大值
总结:
1.输入输出还是花费了15min左右时间才搞定,下次可以提前准备
2.读题目没看清楚,题目写的是对两个公共边位置进行*-1运算,看成对公共边进行运算,导致示例通过,其他无法通过。
package ali;
import java.util.Scanner;
public class a1 {
public static void main(String[] args) {
int [][]nums = new int[0][];
Scanner input = new Scanner(System.in);
int n = 0;
int m = 0;
int count = 0;
String s1 = input.nextLine();
String ss1[] = s1.split(" ");
if(count ==0){
n = Integer.parseInt(ss1[0]);
m = Integer.parseInt(ss1[1]);
if(!(n==0||m==0)){
nums = new int[n][m];
// count++;
}
}
while (count<n) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
String s2 = input.nextLine();
String ss2[] = s2.split(" ");
for(int i = 0;i<m;i++){
nums[count][i] = Integer.parseInt(ss2[i]);
}
count++;
}
int sum = arraySum(nums,n,m);
System.out.println(sum);
}
public static int arraySum(int[][] nums,int n,int m){
// //行最大值
////// int max1 = 0;
////// for(int i = 0;i<n;i++){
////// int temp = 0;
////// int j = 0;
////// for(;j<m;j++){
////// temp +=nums[i][j];
////// }
////// if(temp>0){
////// max1 += temp;
////// }else{
////// max1 += -temp;
////// }
////// }
////// //列最大值
////// int max2 = 0;
////// for(int i = 0;i<m;i++){
////// int temp = 0;
////// int j = 0;
////// for(;j<n;j++){
////// temp +=nums[j][i];
////// }
////// if(temp>0){
////// max2 += temp;
////// }else{
////// max2 += -temp;
////// }
////// }
////// return Math.max(max1,max2);
//记录小于0的数
int count = 0;
int min = Integer.MAX_VALUE;
int sum = 0;
for(int i=0;i<n;i++){
for(int j = 0;j<m;j++){
sum+=Math.abs(nums[i][j]);
if(Math.abs(nums[i][j])<min){
min = Math.abs(nums[i][j]);
}
if(nums[i][j]<=0){
count++;
}
}
}
if(count==0||count%2==0){
return sum;
}else if(count%2==1){
return sum - 2*min;
}
return sum;
}
}
2.有n整数a[i],求所有子串的最大值与最小值的差的和是多少。例如数组1,2,3子串1的最大值与最小值差为0,子串2的最大值与最小值差为0,子串3的最大值与最小值差为0,子串1,2的最大值与最小值差为0,子串1,2的最大值与最小值差为1,子串2,3的最大值与最小值差为1,子串1,2,3的最大值与最小值差为2,总和为4。
输入:
3
1 2 3
输出:
4
时间来不及,第二题没有写。。。
#阿里巴巴##笔经#

