刷leetcode小记2——array(122)
来源:互联网 发布:人力资源分析软件 编辑:程序博客网 时间:2024/06/05 17:49
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
public class Solution {public int maxProfit(int[] prices) {
if (prices.length ==0 ) return 0;
int minPrice = prices[0];
int maxGap = 0;
for (int i = 1; i < prices.length; ++i) {
if(prices[i] - minPrice > maxGap) {
maxGap = prices[i] - minPrice;
}
if (prices[i] < minPrice) {
minPrice = prices[i];
}
}
return maxGap;
}
}
先看第一道题,这道题的关键点在于只有一次交易的过程,所以我们首先设置第一个数为最小,profit为0。然后每次用下一个来减去这个最小的数更新profit的值,如果遇到比最小的数更小的数我们就更新一下最小的数。
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
public class Solution {
public int maxProfit(int[] prices) {
int pro = 0;
if(prices == null){
return pro;
}
for(int i =1; i < prices.length; i++){
if(prices[i-1] < prices[i]){
pro += prices[i] - prices[i-1];
}
}
return pro;
}
}
- 刷leetcode小记2——array(122)
- leetcode小记3——array,string(238,242)
- Leetcode——Array 2
- 【leetcode】Array——Rotate Array(189)
- 【leetcode】Array——Triangle(120)
- 【leetcode】Array——Subsets(78)
- 【leetcode】Array——SubsetsII(90)
- 【leetcode】Array——easy(java)
- LeetCode——Rotate Array
- Leetcode——Array 3
- 刷leetcode小记1——位操作(260,136,137)
- LeetCode刷题小记
- leetcode刷题日记——Merge Sorted Array
- leetcode刷题日记——Rotate Array
- 【leetcode】Array——Search in Rotated Sorted Array(33)
- 【leetcode】Array——Search in Rotated Sorted Array II(81)
- 【leetcode】Array——Remove Duplicates from Sorted Array(26)
- 【leetcode】Array——Remove Duplicates from Sorted Array II(80)
- 1079. Total Sales of Supply Chain (25)
- Fiddler 扩展编程——oSession相关方法
- Fiddler 高级用法:Fiddler Script 与 HTTP 断点调试
- DB9 串口母对母转接头是个坑
- ytrety
- 刷leetcode小记2——array(122)
- Python Module_subprocess_子进程(程序调用)
- mina 客户端无法得到服务器的返回值
- JDBC基本操作:CRUD样例
- [LintCode]Length of Last Word
- use count of shared_ptr
- [计网学习笔记(1)] 计算机网络概述
- [Lintcode]Longest Increasing Continuous Subsequence
- [Lintcode]Longest Words