跳跃游戏 买卖股票的最佳时机

This commit is contained in:
Zerroi 2024-03-08 20:09:41 +08:00
parent 9b4e1b906d
commit c1c43f75f5
4 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package com.zerroi.leetcode.ThreeEight;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class HIndex {
public static void main(String[] args) {
int[] a = new int[]{3,0,6,1,5};
Solution solution = new Solution();
solution.hIndex(a);
}
}
/*给你一个整数数组 citations 其中 citations[i] 表示研究者的第 i 篇论文被引用的次数计算并返回该研究者的 h 指数
根据维基百科上 h 指数的定义h 代表高引用次数 一名科研人员的 h 指数 是指他至少发表了 h 篇论文并且 至少 h 篇论文被引用次数大于等于 h
如果 h 有多种可能的值h 指数 是其中最大的那个*/
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
int index = 0;
for (int i = citations.length - 1; i >= 0; i--) {
if (citations[i] > index) {
index++;
}
}
return index;
}
}

View File

@ -0,0 +1,32 @@
package com.zerroi.leetcode.ThreeFour;
public class MaxProfit {
public static void main(String[] args) {
}
}
class SolutionFirst {
// O(n^2) solution can't access
public int maxProfitFirst(int[] prices) {
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
}
}
return maxProfit;
}
// O(n) solution
public int maxProfit(int[] prices) {
int cost = Integer.MAX_VALUE;
int profit = 0;
for (int price : prices) {
cost = Math.min(cost, price);
profit = Math.max(profit, price - cost);
}
return profit;
}
}

View File

@ -0,0 +1,25 @@
package com.zerroi.leetcode.ThreeFour;
public class MaxProfit {
}
/*
给你一个整数数组 prices 其中 prices[i] 表示某支股票第 i 天的价格
在每一天你可以决定是否购买和/或出售股票你在任何时候 最多 只能持有 一股 股票你也可以先购买然后在 同一天 出售
返回 你能获得的 最大 利润
*/
class SolutionSecond {
public int maxProfit(int[] prices) {
int profit = 0;
int n = prices[0];
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i + 1] > prices[i]) {
profit += prices[i + 1] - prices[i];
}
}
return profit;
}
}

View File

@ -0,0 +1,23 @@
package com.zerroi.leetcode.ThreeSeven;
import org.w3c.dom.css.CSSStyleDeclaration;
public class CanJump {
}
/*
* 给你一个非负整数数组 nums 你最初位于数组的 第一个下标 数组中的每个元素代表你在该位置可以跳跃的最大长度
判断你是否能够到达最后一个下标如果可以返回 true 否则返回 false
* */
class SolutionFirst {
public boolean canJump(int[] nums) {
int step = 0;
for (int i = 0; i < nums.length; i++) {
// 当前位置可以跳跃的最大长度
step = Math.max(step, nums[i] + i);
if (step >= nums.length - 1) return true;
}
return false;
}
}