2018滴滴校招(秋招)内推笔试编程题题解

时间:2022-04-13 13:51:57

2018滴滴校招(秋招)内推笔试编程题题解

package 内推笔试;

import java.util.Arrays;
import java.util.Scanner;

/**
* Created by liuming on 2017/8/26.
*/

public class 滴滴 {

/**
* 给定整数序列求最大连续字串和
* <p>
* 问题描述:
* 给定无序正数序列,求连续字串最大和,例如:{-23,17,-7,11,-2,1,34},字串为{17,-7,11,},最大和为21
*/

public static int getTargetMax(int[] arr) {
int max = arr[0];
int tmpMax = arr[0];
for (int i = 1; i < arr.length; i++) {
if (tmpMax <= 0)
tmpMax = arr[i];
else
tmpMax += arr[i];
if (tmpMax > max) {
max = tmpMax;
}
}
return max;
}

public static void main1(String[] args) {
Scanner sc = new Scanner(System.in);
//获取输入的整数序列
String str = sc.nextLine();
String[] strings = str.split(" ");
//转为整数数组
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
System.out.println(getTargetMax(ints));
}

/**
* 整数无序数组求第K大数
* <p>
* 问题描述:
* 给定无序整数序列,求其中第K大的数,例如{45,67,33,21},第2大的数为45
*/

public static int getTopK(int[] arr, int k) {
Arrays.sort(arr);
return arr[arr.length - k];
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//获取输入的整数序列
String str = sc.nextLine();
String[] strings = str.split(" ");
//转为整数数组
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
int k = sc.nextInt();
System.out.println(getTopK(ints, k));
}

}

2018滴滴校招(秋招)内推笔试编程题题解