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

相关推荐
l1t1 天前
postgresql递归查询指定搜索顺序的方法
数据库·postgresql·dfs·递归·cte
l1t1 天前
sqlite递归查询指定搜索顺序的方法
数据库·sql·sqlite·dfs·递归·cte
yaoh.wang7 天前
力扣(LeetCode) 70: 爬楼梯 - 解法思路
python·算法·leetcode·面试·职场和发展·动态规划·递归
DanyHope8 天前
LeetCode 206. 反转链表:迭代 + 递归双解法全解析
算法·leetcode·链表·递归·迭代
oscar99911 天前
CSP-J教程——第一阶段第十一课:函数与递归初步
递归·函数·csp-j
长安er11 天前
LeetCode 46/51 排列型回溯题笔记-全排列 / N 皇后
笔记·算法·leetcode·回溯·递归·n皇后
鹿角片ljp14 天前
力扣104.求二叉树最大深度:递归和迭代
算法·leetcode·二叉树·递归
长安er14 天前
LeetCode 235 & 236 最近公共祖先(LCA)解题总结
算法·leetcode·二叉树·递归·lca
长安er16 天前
LeetCode 100/101/110/199 对称/平衡二叉树与右视图
算法·leetcode·二叉树·dfs·bfs·递归