码迷,mamicode.com
首页 > 编程语言 > 详细

找出数组中所有组合中最大的值

时间:2018-12-08 00:19:55      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:控制   length   nbsp   算法   style   code   获取   组合   .com   

面试中,经常有算法题:

比如找出一个数组中的所有组合,并找出最大的值。

代码如下:

 1 package com.company.algorithm;
 2 
 3 /**
 4  * 选择数组中和的值最大的一组,例如:[2,-7,5,-9],组大的一组是:2,-7,5值为0
 5  */
 6 public class SelectValueMaxGroup {
 7     public static void main(String[] args) {
 8         int[] list = {6, -1, 2, -9, 4, -5, 7, -8, 3, -10, 15};
 9         int max = getMax(list);
10         System.out.println(max);
11     }
12 
13     /**
14      * 获取值最大的那组的值
15      * 算法:
16      * 1. 如何找到所以的分组?设数组长度为n,则组的个数=n-1 + n - 2 + ...1 即: (n - 1) * (n - 1 + 1) / 2 ;
17      *    例如数组长度为10,则根据公式:(10 - 1) * ( 10 - 1 + 1) / 2 = 45中组合
18      * 2. 依次从第一个元素开始找与它所有的组合,直到找到最后一个组合
19      * 3. 计算每个组合的值,找到最大的
20      * @param list 数组
21      * @return 组合最大的值
22      */
23     private static int getMax(int[] list) {
24         int max = 0;
25         int temp;
26         //从第一个元素开始组合,逐次到数组最大长度
27         for (int i = 0; i < list.length - 2; i++) {
28             //控制组合,由索引m递增控制
29             for (int m = i + 1; m <= list.length - 1; m++) {
30                 temp = getValue(list, i, m);
31                 if (temp != max && temp > max) {
32                     max = temp;
33                 }
34             }
35         }
36         return max;
37     }
38 
39     /**
40      * 获取数组从索引开始大结束的值,及组合的值
41      * @param list 数组
42      * @param start 开始索引
43      * @param end 结束索引
44      * @return 组合的值
45      */
46     private static int getValue(int[] list, int start, int end) {
47         int temp = 0;
48         for (int i = start; i <= end; i++) {
49             temp += list[i];
50         }
51 
52         return temp;
53     }
54 }

 

找出数组中所有组合中最大的值

标签:控制   length   nbsp   算法   style   code   获取   组合   .com   

原文地址:https://www.cnblogs.com/feiyujun/p/10085849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!