【LEETCODE】37、122题,Best Time to Buy and Sell Stock II
2024-10-20 15:40:44
package y2019.Algorithm.array; /**
* @ProjectName: cutter-point
* @Package: y2019.Algorithm.array
* @ClassName: MaxProfit2
* @Author: xiaof
* @Description: 122. Best Time to Buy and Sell Stock II
* 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
* (i.e., buy one and sell one share of the stock multiple times).
*
* Input: [7,1,5,3,6,4]
* Output: 7
* Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
* Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
*
* 你可以尽可能多的进行交易
* 那么这个题就是有的赚就买的意思了
*
* @Date: 2019/7/2 10:12
* @Version: 1.0
*/
public class MaxProfit2 { public int solution(int[] prices) {
//那就是贪心算法了
Integer curSmall = 0, result = 0;
if(prices.length == 0)
return 0; //没得赚
else {
curSmall = prices[0];
} for(int i = 1; i < prices.length; ++i) {
int temp = prices[i]; if(curSmall == null || temp < curSmall) {
curSmall = temp;
} else if(temp > curSmall) {
result += temp - curSmall;
curSmall = temp;
}
} return result;
} public static void main(String args[]) { int pres[] = {1,2,3,4,5};
System.out.println(new MaxProfit2().solution(pres)); } }
最新文章
- input输入时光标位置靠上问题解决
- 手把手系列:实现Nat地址转换
- jQuery入门第一天
- 【iCore3 双核心板_ uC/OS-III】例程二:任务的建立与删除
- Codeforces Flipping game 动态规划基础
- Linux进程调度原理
- Google Map和桌面组件 Android开发教程
- 【C#】获取本地Cookie的问题
- 【POJ3580】【splay版】SuperMemo
- WebView高危接口安全检测
- javascript每日一练(九)——运动一:匀速运动
- Android项目----dispathTouchEvent
- latex beamer 添加页码
- Django请求生命周期
- apache和nginx结合使用
- [C++]Linux之进程间通信小结【待完善】
- 消息队列:JMS之基本概念介绍
- fresco xml配置属性不起作用
- 将本地 项目文件托管到 github
- selenium之 chromedriver与chrome版本映射表(更新至v2.34)