【极客app每日一练】【Geeks for Geeks】Java: 最大索引差

14 篇文章 0 订阅

Problem

Given an array a of n positive integers. The task is to find the maximum of j - i subject to the constraint of a[i] <= a[j] and i <= j.

Examples

Example 1

n = 2
a[] = {1, 10}
Output: 1 (a[1] >= a[0])

Example 2

n = 9
a[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}
Output: 6 (a[7] >= a[1])

Complexity Constraints

Time complexity: O(N)

Auxiliary space: O(N)

Parameter Constraints

1 <= n <= 10 ^ 6

0 <= a[i] <= 10 ^ 9

Answer (in Java)

2024年3月5日,于印度尼西亚巴厘岛

/* By LI YI CHEN on 2024/3/5, in BALI Indonesia */
import java.util.Scanner;

public class Maximum_Index
{
    public static void main(String[] args)
    {
        int n, i;
        int temp;
        int[] arr = new int[1000001];

        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter n:");
        n = scanner.nextInt();

        System.out.println("Enter n elements for array: ");
        for (i = 0; i < n; i++)
        {
            arr[i] = scanner.nextInt();
        }

        int j, k;  // pointer variables

        int maximum_index = 0;  // the answer, initialized to 0
        // Core code
        for (j = 0;j <= n - 1;j ++)
        {
            for (k = n - 1;k >= j;k --)
            {
                if (arr[k] >= arr[j] && k - j > maximum_index)
                {
                    maximum_index = k - j;
                }
            }
        }

        System.out.println("The required maximum index is: " + maximum_index);
        System.out.println("Program finished. Good day.");
    }
}

运行示例

示例1:

在这里插入图片描述

示例2:

在这里插入图片描述

思路简述

本题的解题思路比较简洁直观:定义2个指针 j 和 k,其中 j 从数组的头部开始迭代自增,k 从数组的末尾(由于题目要求最大的索引差,从末尾开始会比较快)迭代自减,满足条件则更新答案变量Maximum_Index,最后将Maximum_Index输出即可。核心代码由一个2次嵌套的for循环构成:

        int maximum_index = 0;  // the answer, initialized to 0
        // Core code
        for (j = 0;j <= n - 1;j ++)
        {
            for (k = n - 1;k >= j;k --)
            {
                if (arr[k] >= arr[j] && k - j > maximum_index)
                {
                    maximum_index = k - j;
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不是AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值