东方博宜OJ 1683:递归法求最大值 ← 递归

【题目来源】
https://oj.czos.cn/p/1683

【题目描述】
请使用递归求 N 个数中的最大数及其位置。

【输入格式】
第一行一个整数 N,N≤1000。
第二行,N 个不重复的整数。

【输出格式】
最大值和其位置。

【输入样例】
10
2 4 1 6 3 10 9 7 8 5

【输出样例】
10 6

【数据范围】
N≤1000

【算法分析】
● 要善于变通,要学会从不同角度进行思考,来构建递归函数。

【算法代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

const int maxn=1e3+5;
int a[maxn];

int f(int n) { //求前n个数的最大值的下标
    if(n==1) return 1;
    int x=f(n-1);
    if(a[x]>a[n]) return x;
    else return n;
}

int main() {
    int n;
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>a[i];
    }

    cout<<a[f(n)]<<" "<<f(n);

    return 0;
}

/*
in:
10
2 4 1 6 3 10 9 7 8 5

out:
10 6
*/

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/156211550
https://blog.csdn.net/hnjzsyjyj/article/details/156206151
https://blog.csdn.net/hnjzsyjyj/article/details/156206554
https://blog.csdn.net/hnjzsyjyj/article/details/156201255
https://blog.csdn.net/hnjzsyjyj/article/details/156192874
https://blog.csdn.net/hnjzsyjyj/article/details/156204715
https://blog.csdn.net/hnjzsyjyj/article/details/156185382
https://blog.csdn.net/hnjzsyjyj/article/details/156182882
https://www.bilibili.com/video/BV1TW4y1K7YK/

相关推荐
Tisfy8 天前
LeetCode 761.特殊的二进制字符串:分治(左右括号对移动)
算法·leetcode·字符串·递归·分治
Bear on Toilet9 天前
递归_二叉树_50 . 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·深度优先·递归
Bear on Toilet11 天前
递归_二叉树_49 . 路径综合Ⅲ
数据结构·算法·前缀和·深度优先·递归
码农幻想梦12 天前
3483. 2的幂次方(上海交通大学考研机试题目)
递归·分治
代码不停17 天前
递归题目练习
java·算法·递归
少许极端18 天前
算法奇妙屋(二十九)-递归、回溯与剪枝的综合问题 2
算法·深度优先·剪枝·回溯·递归
老鼠只爱大米18 天前
LeetCode经典算法面试题 #22:括号生成(回溯法、动态规划、闭合数法等五种实现方案解析)
算法·leetcode·动态规划·递归·回溯算法·卡特兰数·括号生成
I_LPL20 天前
day21 代码随想录算法训练营 二叉树专题8
算法·二叉树·递归
少许极端20 天前
算法奇妙屋(二十八)-递归、回溯与剪枝的综合问题 1
java·算法·深度优先·剪枝·回溯·递归
2401_8414956420 天前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归