东方博宜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/

相关推荐
少许极端1 天前
算法奇妙屋(二十五)-递归问题
算法·递归·汉诺塔
EXtreme359 天前
【数据结构】彻底搞懂二叉树:四种遍历逻辑、经典OJ题与递归性能全解析
c语言·数据结构·算法·二叉树·递归
汉克老师10 天前
GESP2025年12月认证C++八级真题与解析(单选题10-12)
c++·递归··gesp八级·gesp8级
jackyrongvip17 天前
10个动画介绍递归(用Gemin3生成)
数据结构·递归·gemin3
l1t21 天前
DeepSeek对利用DuckDB求解Advent of Code 2021第9题“烟雾盆地”第二部分SQL的分析
数据库·人工智能·sql·递归·duckdb·deepseek·cte
l1t23 天前
postgresql递归查询指定搜索顺序的方法
数据库·postgresql·dfs·递归·cte
l1t23 天前
sqlite递归查询指定搜索顺序的方法
数据库·sql·sqlite·dfs·递归·cte
yaoh.wang1 个月前
力扣(LeetCode) 70: 爬楼梯 - 解法思路
python·算法·leetcode·面试·职场和发展·动态规划·递归
DanyHope1 个月前
LeetCode 206. 反转链表:迭代 + 递归双解法全解析
算法·leetcode·链表·递归·迭代